Как динамически установить текстовое значение из json во флаттере

Привет, друзья, как динамически установить текстовое значение Я использую JSON для получения данных, но когда я обновляю данные, заполняются, и я вызываю JSON в initstate для каждой загрузки до того, как страница приложения запустится, извините, друзья, я не много знаю о флаттере, поэтому, пожалуйста, помогите мне с этим, пожалуйста, найдите код ниже

String name, userimage, birth, c_id, email, mobile_number;

class Profile extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    Profile_Customer profile_customer() => Profile_Customer();
    return profile_customer();
  }
}

class Profile_Customer extends State<Profile> {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('Profile'),
          backgroundColor: primarycolor,
          leading: new IconButton(
              icon: new Icon(Icons.arrow_back),
              onPressed: () {
                Navigator.pushReplacement(
                    context,
                    new MaterialPageRoute(
                        builder: (context) => new HomeScreen()));
              }),
        ),
        body: new Builder(builder: (BuildContext context) {
          return new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new Container(
                child: new Image.asset('assets/rural_post_logo.png',
                    fit: BoxFit.cover),
                margin: EdgeInsets.only(bottom: 15.0),
              ),
              new Container(
                child: new CircleAvatar(
                  child: new Image.network(userimage,
                      width: 100.0, height: 100.0, fit: BoxFit.cover),
                ),
                margin: EdgeInsets.only(top: 10.0),
                alignment: Alignment(0.0, 0.0),
              ),
              new Container(
                child: new Text(name),
                margin: EdgeInsets.only(top: 10.0),
              ),
              new Container(
                child: new Divider(
                  height: 2.0,
                  color: primarycolor,
                ),
                margin: EdgeInsets.only(right: 10.0, left: 10.0, top: 10.0),
              ),
              new Container(
                child: new Text(
                  'Birth Date',
                  style: new TextStyle(
                      fontWeight: FontWeight.bold, fontSize: 16.0),
                ),
                alignment: Alignment(-1.0, 0.0),
                margin: EdgeInsets.only(top: 10.0, left: 10.0),
              ),
              new Container(
                child: new Text(birth),
                alignment: Alignment(-1.0, 0.0),
                margin: EdgeInsets.only(top: 10.0, left: 10.0),
              ),
              new Container(
                child: new Divider(
                  height: 2.0,
                  color: primarycolor,
                ),
                margin: EdgeInsets.only(right: 10.0, left: 10.0, top: 10.0),
              ),
              new Container(
                child: new Text(
                  'Customer ID',
                  style: new TextStyle(
                      fontWeight: FontWeight.bold, fontSize: 16.0),
                ),
                alignment: Alignment(-1.0, 0.0),
                margin: EdgeInsets.only(top: 10.0, left: 10.0),
              ),
              new Container(
                child: new Text(c_id),
                alignment: Alignment(-1.0, 0.0),
                margin: EdgeInsets.only(top: 10.0, left: 10.0),
              ),
              new Container(
                child: new Divider(
                  height: 2.0,
                  color: primarycolor,
                ),
                margin: EdgeInsets.only(right: 10.0, left: 10.0, top: 10.0),
              ),
              new Container(
                child: new Text(
                  'Email',
                  style: new TextStyle(
                      fontWeight: FontWeight.bold, fontSize: 16.0),
                ),
                alignment: Alignment(-1.0, 0.0),
                margin: EdgeInsets.only(top: 10.0, left: 10.0),
              ),
              new Container(
                child: new Text(email),
                alignment: Alignment(-1.0, 0.0),
                margin: EdgeInsets.only(top: 10.0, left: 10.0),
              ),
              new Container(
                child: new Divider(
                  height: 2.0,
                  color: primarycolor,
                ),
                margin: EdgeInsets.only(right: 10.0, left: 10.0, top: 10.0),
              ),
              new Container(
                child: new Text(
                  'Mobile number',
                  style: new TextStyle(
                      fontWeight: FontWeight.bold, fontSize: 16.0),
                ),
                alignment: Alignment(-1.0, 0.0),
                margin: EdgeInsets.only(top: 10.0, left: 10.0),
              ),
              new Container(
                child: new Text(mobile_number),
                alignment: Alignment(-1.0, 0.0),
                margin: EdgeInsets.only(top: 10.0, left: 10.0),
              ),
              new Container(
                child: new RaisedButton(
                  onPressed: () {
                    Navigator.push(
                        context,
                        new MaterialPageRoute(
                            builder: (context) => new HomeScreen()));
                  },
                  color: secondarycolor,
                  shape: new RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(5.0)),
                  child: new Text('Update Profile',
                      style: new TextStyle(color: Colors.white)),
                ),
                width: 300.0,
                height: 40.0,
                margin: EdgeInsets.only(top: 10.0),
              )
            ],
          );
        }),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    profilejson();
  }
}

void profilejson() async {
  SharedPreferences pref = await SharedPreferences.getInstance();
  var profile_url = url + "view_profile&userid=" + pref.getString('userid');
  print(profile_url);
  http.Response profileresponse = await http.get(profile_url);
  var profile_response_json = json.decode(profileresponse.body);
  name = profile_response_json['username'];
  userimage = profile_response_json['image'];
  birth = profile_response_json['dob'];
  c_id = profile_response_json['customerid'];
  email = profile_response_json['email'];
  mobile_number = profile_response_json['phone'];
}

person ayub baba    schedule 27.06.2018    source источник
comment
Это не связано с программированием. Это просто поможет вам писать понятные вопросы и ответы на StackOverflow: Когда использовать? (определенный артикль)   -  person creativecreatorormaybenot    schedule 27.06.2018


Ответы (1)


Этого можно добиться с помощью StatefulWidget и setState, позволяющих изменять макет на ходу. Поскольку у вас уже есть виджет в вашем коде, вы должны просто вызвать setState, если вы установили свои переменные. Также profilejson() должны мы в штате:

...
profilejson() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    var profile_url = url + "view_profile&userid=" + pref.getString('userid');
    print(profile_url);
    http.Response profileresponse = await http.get(profile_url);
    var profile_response_json = json.decode(profileresponse.body);

    // the variables you want the layout to be updated with
    setState(() {
        name = profile_response_json['username'];
        userimage = profile_response_json['image'];
        birth = profile_response_json['dob'];
        c_id = profile_response_json['customerid'];
        email = profile_response_json['email'];
        mobile_number = profile_response_json['phone'];
    })
}   

@override
void initState() {
    super.initState();
    profilejson();
}
...

Полный код:

String name, userimage, birth, c_id, email, mobile_number;

class Profile extends StatefulWidget {
@override
State<StatefulWidget> createState() {
    Profile_Customer profile_customer() => Profile_Customer();
    return profile_customer();
}
}

class Profile_Customer extends State<Profile> {
@override
Widget build(BuildContext context) {
    return new MaterialApp(
    home: new Scaffold(
        appBar: new AppBar(
        title: new Text('Profile'),
        backgroundColor: primarycolor,
        leading: new IconButton(
            icon: new Icon(Icons.arrow_back),
            onPressed: () {
                Navigator.pushReplacement(
                    context,
                    new MaterialPageRoute(
                        builder: (context) => new HomeScreen()));
            }),
        ),
        body: email != null ? new Builder(builder: (BuildContext context) {
        return new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
            new Container(
                child: new Image.asset('assets/rural_post_logo.png',
                    fit: BoxFit.cover),
                margin: EdgeInsets.only(bottom: 15.0),
            ),
            new Container(
                child: new CircleAvatar(
                child: new Image.network(userimage,
                    width: 100.0, height: 100.0, fit: BoxFit.cover),
                ),
                margin: EdgeInsets.only(top: 10.0),
                alignment: Alignment(0.0, 0.0),
            ),
            new Container(
                child: new Text(name),
                margin: EdgeInsets.only(top: 10.0),
            ),
            new Container(
                child: new Divider(
                height: 2.0,
                color: primarycolor,
                ),
                margin: EdgeInsets.only(right: 10.0, left: 10.0, top: 10.0),
            ),
            new Container(
                child: new Text(
                'Birth Date',
                style: new TextStyle(
                    fontWeight: FontWeight.bold, fontSize: 16.0),
                ),
                alignment: Alignment(-1.0, 0.0),
                margin: EdgeInsets.only(top: 10.0, left: 10.0),
            ),
            new Container(
                child: new Text(birth),
                alignment: Alignment(-1.0, 0.0),
                margin: EdgeInsets.only(top: 10.0, left: 10.0),
            ),
            new Container(
                child: new Divider(
                height: 2.0,
                color: primarycolor,
                ),
                margin: EdgeInsets.only(right: 10.0, left: 10.0, top: 10.0),
            ),
            new Container(
                child: new Text(
                'Customer ID',
                style: new TextStyle(
                    fontWeight: FontWeight.bold, fontSize: 16.0),
                ),
                alignment: Alignment(-1.0, 0.0),
                margin: EdgeInsets.only(top: 10.0, left: 10.0),
            ),
            new Container(
                child: new Text(c_id),
                alignment: Alignment(-1.0, 0.0),
                margin: EdgeInsets.only(top: 10.0, left: 10.0),
            ),
            new Container(
                child: new Divider(
                height: 2.0,
                color: primarycolor,
                ),
                margin: EdgeInsets.only(right: 10.0, left: 10.0, top: 10.0),
            ),
            new Container(
                child: new Text(
                'Email',
                style: new TextStyle(
                    fontWeight: FontWeight.bold, fontSize: 16.0),
                ),
                alignment: Alignment(-1.0, 0.0),
                margin: EdgeInsets.only(top: 10.0, left: 10.0),
            ),
            new Container(
                child: new Text(email),
                alignment: Alignment(-1.0, 0.0),
                margin: EdgeInsets.only(top: 10.0, left: 10.0),
            ),
            new Container(
                child: new Divider(
                height: 2.0,
                color: primarycolor,
                ),
                margin: EdgeInsets.only(right: 10.0, left: 10.0, top: 10.0),
            ),
            new Container(
                child: new Text(
                'Mobile number',
                style: new TextStyle(
                    fontWeight: FontWeight.bold, fontSize: 16.0),
                ),
                alignment: Alignment(-1.0, 0.0),
                margin: EdgeInsets.only(top: 10.0, left: 10.0),
            ),
            new Container(
                child: new Text(mobile_number),
                alignment: Alignment(-1.0, 0.0),
                margin: EdgeInsets.only(top: 10.0, left: 10.0),
            ),
            new Container(
                child: new RaisedButton(
                onPressed: () {
                    Navigator.push(
                        context,
                        new MaterialPageRoute(
                            builder: (context) => new HomeScreen()));
                },
                color: secondarycolor,
                shape: new RoundedRectangleBorder(
                    borderRadius: new BorderRadius.circular(5.0)),
                child: new Text('Update Profile',
                    style: new TextStyle(color: Colors.white)),
                ),
                width: 300.0,
                height: 40.0,
                margin: EdgeInsets.only(top: 10.0),
            )
            ],
        );
        }) : new Center(child: new CircularProgressIndicator()),
    ),
    );
}

    profilejson() async {
        SharedPreferences pref = await SharedPreferences.getInstance();
        var profile_url = url + "view_profile&userid=" + pref.getString('userid');
        print(profile_url);
        http.Response profileresponse = await http.get(profile_url);
        var profile_response_json = json.decode(profileresponse.body);

        // the variables you want the layout to be updated with
        setState(() {
            name = profile_response_json['username'];
            userimage = profile_response_json['image'];
            birth = profile_response_json['dob'];
            c_id = profile_response_json['customerid'];
            email = profile_response_json['email'];
            mobile_number = profile_response_json['phone'];
        })
    }   

    @override
    void initState() {
        super.initState();
        profilejson();
    }
}
person Bostrot    schedule 27.06.2018
comment
Сначала отображается ошибка, затем отображаются данные - person ayub baba; 28.06.2018
comment
Вы можете включить оператор if, чтобы увидеть, загружен ли json или нет. Оберните свой виджет под телом email != null ? all_your_widgets_under_body : Center(child: CircularProgressbar()) - person Bostrot; 28.06.2018
comment
не могли бы вы предоставить полный код, которого я не понял, извините за проблемы - person ayub baba; 28.06.2018
comment
Вы просто помещаете email != null ? перед new Builder и : Center(child: CircularProgressbar()) после конструктора виджетов. - person Bostrot; 28.06.2018
comment
body: email! = null? имя! = ноль? userimage! = null? рождение! = ноль? c_id! = null? c_id! = null? : Center (дочерний: CircularProgressIndicator (),) - person ayub baba; 28.06.2018
comment
Логический оператор &&, поэтому что-то вроде email != null && name != null, ? похоже на then. И вы не должны :, который похож на else. - person Bostrot; 28.06.2018
comment
не может отобразить вид загружается только круговой загрузчик - person ayub baba; 28.06.2018
comment
Было выдано следующее утверждение Building Builder (грязное): 'package: flutter / src / painting / image_provider.dart': Неудачное утверждение: строка 405 поз. 16: 'url! = - person ayub baba; 28.06.2018
comment
Я добавил полный код выше. (нужно проверить только одну переменную) - person Bostrot; 28.06.2018
comment
Братан, если возможно, помогите мне и с этим stackoverflow.com/questions/51075166/ извините за беспокойство - person ayub baba; 28.06.2018
comment
Love u Bro, это сработало отлично, и спасибо, что объяснили насчет этого? и : - person ayub baba; 28.06.2018