我们如何访问颤振小部件中的列表项?

时间:2021-06-12 15:31:36

标签: flutter dart

我试图从我的 Future 函数中创建的列表中访问 fullName,但无法做到。我通过索引进行了尝试,这种方法我已经尝试过 snapshot.data.fullName,但仍然无法检索数据,即使从 future 函数返回后我也遇到了问题。

下面是用户模型的代码

class User {
   final String fullname; 
   final String contactno;
   final String address;
   final String city;
   final String gender;
   final String email;

   
   User(this.fullname, this.contactno, this.address, this.city, this.gender, this.email); 
   factory User.fromMap(Map<String, dynamic> json) { 
      return User( 
         json['fullname'], 
         json['contactno'], 
         json['address'], 
         json['city'], 
         json['gender'], 
         json['email']
      );
   }
}

有状态的类代码

class EditProfile extends StatefulWidget {
  // final String user_fullname;
  // //const EditProfile(this.user_fullname);
  //  const EditProfile ({ Key key, this.user_fullname}): super(key: key);

  @override
  _EditProfileState createState() => _EditProfileState();
}

Future<List<User>> getData() async {
  var id = "26";
  var url = baseurl + patientData + id;
  var data;
  var rest;
  print('Calling uri: $url');
  // 4
  http.Response response = await http.get(url);
  // 5
  if (response.statusCode == 200) {
    data = response.body;
    print(data);
  } else {
    print(response.statusCode);
  }

  //Map<String, dynamic> user = jsonDecode(data);
  var jsonData = jsonDecode(data.body);

  List<User> users = [];

  for (var u in jsonData) {
    User user = User(u['fullname'], u['contactno'], u['address'], u['city'], u['gender'], u['email']);
    users.add(user);
  }
  // print(users.length.toString);
}

我想在文本小部件的未来函数中访问上面列表中的 fullName,我在下面使用了 snapshot.data.fullName

class _EditProfileState extends State<EditProfile> {
  @override
  void initState() {
    super.initState();
    getData();
  }
  @override
  Widget build(BuildContext context) {
    getData().then((value) {
      print(value);
    });

    return FutureBuilder(
      future: getData(),
      // ignore: missing_return
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return WillPopScope(
            onWillPop: () {},
            child: Scaffold(
              appBar: AppBar(title: Text("Your Profile"), automaticallyImplyLeading: false, actions: <Widget>[
                IconButton(
                  icon: Icon(
                    Icons.logout,
                    color: Colors.white,
                  ),
                  onPressed: () {
                    Navigator.push(context, MaterialPageRoute(builder: (context) => PatientDashboard()));
                  },
                )
              ]),
              body: SingleChildScrollView(
                child: Container(
//       color: Colors.pink,
                  child: Column(
                    children: [
                      Center(
                        child: Padding(
                          padding: const EdgeInsets.only(top: 18.0),
                          child: Container(
                            //   color: kPrimaryLightColor,
                            child: Stack(
                              children: [
                                //Image
                                CircleAvatar(
                                  radius: 100,
                                  backgroundColor: Colors.red[900],
                                  child: CircleAvatar(
                                    radius: 95,
                                    backgroundImage: _pic == null ? AssetImage("assets/images/doctor2.jpg") : FileImage(_pic),
                                  ),
                                ),
                                Positioned(
                                  bottom: 5,
                                  right: 15,
                                  child: CircleAvatar(
                                    backgroundColor: Colors.cyanAccent,
                                    child: GestureDetector(
                                        onTap: () {
                                          setState(() {
                                            //firstname = widget.user_fullname;
                                            getImage();
                                            state = 19;
                                          });
                                        },
                                        child: Icon(Icons.camera_alt)),
                                    radius: 20,
                                  ),
                                )
                              ],
                            ),
                          ),
                        ),
                      ),
                      //Name
                      Container(
                        width: double.infinity,
                        //color: Colors.grey[400],
                        child: Stack(
                          children: [
                            Center(
                              child: Padding(
                                padding: const EdgeInsets.only(left: 18.0, top: 20),
                                child: Container(
                                  //color: Colors.cyan[50],
                                  width: MediaQuery.of(context).size.width * 0.78,
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text("Name"),
                                      Padding(
                                        padding: const EdgeInsets.only(top: 2.0),
                                        child: state == 1
                                            ? TextField(
                                                decoration: InputDecoration(border: InputBorder.none, hintText: "${snapshot.data}", hintStyle: TextStyle(fontSize: 17, fontWeight: FontWeight.bold)), //style: TextStyle(under),
                                                onChanged: (text) {
                                                  firstname = text;
                                                },
                                              )
                                            : Text(
                                                snapshot.data.fullName,
                                                style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold),
                                              ),
                                      )],
      else {
          return Center(child: CircularProgressIndicator());
        }
      },
    );
  }
}

但我收到此错误

Error: NoSuchMethodError: 'body'
method not found
```
Arguments: []
    at Object.throw_ [as throw] (http://localhost:59886/dart_sdk.js:5333:11)
    at Object.defaultNoSuchMethod (http://localhost:59886/dart_sdk.js:5778:15)
    at String.noSuchMethod (http://localhost:59886/dart_sdk.js:6878:19)
    at Object.noSuchMethod (http://localhost:59886/dart_sdk.js:5774:30)
    at Object.dload (http://localhost:59886/dart_sdk.js:5395:17)
    at getData (http://localhost:59886/packages/newfypapproach/patient/screens/patientForgotPassword.dart.lib.js:12720:64)
    at getData.next (<anonymous>)
    at http://localhost:59886/dart_sdk.js:39031:33
    at _RootZone.runUnary (http://localhost:59886/dart_sdk.js:38888:58)
    at _FutureListener.thenAwait.handleValue (http://localhost:59886/dart_sdk.js:33874:29)
    at handleValueCallback (http://localhost:59886/dart_sdk.js:34434:49)
    at Function._propagateToListeners (http://localhost:59886/dart_sdk.js:34472:17)
    at _Future.new.[_completeWithValue] (http://localhost:59886/dart_sdk.js:34314:23)
    at async._AsyncCallbackEntry.new.callback (http://localhost:59886/dart_sdk.js:34337:35)
    at Object._microtaskLoop (http://localhost:59886/dart_sdk.js:39175:13)
    at _startMicrotaskLoop (http://localhost:59886/dart_sdk.js:39181:13)
    at http://localhost:59886/dart_sdk.js:34688:9
```

我使用了这种不同的方法来创建一个返回字符串列表的未来函数,并且该列表可以完美地包含所有值。

```
Future<List<String>> getData() async {
  var id = "26";
  var url = baseurl + patientData + id;
  var data;
  var rest;
  print('Calling uri: $url');
  // 4
  http.Response response = await http.get(url);
  // 5
  if (response.statusCode == 200) {
    data = response.body;
    print(data);
    // rest = data['result'] as List;
    // print(rest);
    //print(data);
  } else {
    print(response.statusCode);
  }

  Map<String, dynamic> user = jsonDecode(data);
  
  // var name = user['result']['name'];
  String fullName = user['result'][0][0];
  String contactNo = user['result'][0][1];
  String address = user['result'][0][2];
  String city = user['result'][0][3];
  String gender = user['result'][0][4];
  String email = user['result'][0][5];

  return <String>[fullName, contactNo, address, city, gender, email];

}

1 个答案:

答案 0 :(得分:0)

如下更改您的 getData

    Future<List<User>> getData() async {
      var id = "26";
      var url = baseurl + patientData + id;
      Map<String, dynamic> data ={};
      var rest;
      // 4
      http.Response response = await http.get(url);
      // 5
      if (response.statusCode == 200) {
        data = response.body;
        print(data);
      } else {
        print(response.statusCode);
      }
    
      //Map<String, dynamic> user = jsonDecode(data);
      var jsonData = jsonDecode(data);
    
      List<User> users = [];
    
      for (var u in jsonData) {
        User user = User(u['fullname'], u['contactno'], u['address'], u['city'], u['gender'], u['email']);
        users.add(user);
      }
     return users; }