как работать с картой строки и списка во флаттере

#flutter #dart #odoo

#трепетать #дротик #одоо

Вопрос:

Я провел несколько поисков в Google, но ничего полезного не нашел. Я бился головой о некоторые ошибки, пытаясь сделать что-то, что должно быть довольно простым. извлекайте данные из списка словаря при подключении к Odoo с помощью OdooApi, чтобы отобразить их в виде списка или в любом подходящем дизайне :

1 — создание home_page.dart , содержащего текстовое поле, в которое можно добавить id в качестве вменяемого

 . . child : TextField(  decoration: new InputDecoration(  focusedBorder: UnderlineInputBorder(  borderSide: BorderSide(color: Colors.red)),  enabledBorder: UnderlineInputBorder(  borderSide: BorderSide(color: Colors.redAccent)  ),  filled: false,  //fillColor: Color(0xFFBB162B),  hintText: "Numéro d'OR",  ),  onChanged: (text){  num_or = text;  },    ),  ),  Expanded(  child: Center(  child: RawMaterialButton(  onPressed: () {_navigateAndDisplayCheckScreen(num_or);},   shape: const StadiumBorder(),  fillColor: AppColor.secondaryColor,  child: const Padding(  padding:  EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0),  child: Text(  "Vérifier",  style: TextStyle(  color: Colors.white,  fontSize: 26.0,  fontWeight: FontWeight.bold,  ), . .   Futurelt;voidgt; _navigateAndDisplayCheckScreen(num_or) async {  final result = await Navigator.of(context).push(  MaterialPageRoute(builder: (context) =gt; CheckScreen( num_or: num_or)),  ); }  

2 — создание check_screen.dart для :

 class CheckScreen extends StatefulWidget {   // CheckScreen({key, num_or}) : super(key: key);   String id;  CheckScreen({this.id});   @override  _CheckScreenState createState() =gt; _CheckScreenState();  }   class _CheckScreenState extends Statelt;CheckScreengt; {   var dt;  String id;  _CheckScreenState({this.id});    Futurelt;OdooResponsegt; _getDataFromServer(id) async {  OdooResponse result;  OdooResponse res = await client  .authenticate(email, password, database)  .then((auth) async {  if (auth.isSuccess) {  print('success');  result =  await client.searchRead('account.invoice', [  ['id', '=', id]  ], [  'id',  'name',  'number',  'service_source',  'origin_invoice'  ]);  print(result.getResult()['records']);   final resu = result.getResult()['records'];  // the error is here  result = resu;   return result;  } else {  print("Login Gagal");  return result;  }  });   }   @override  Widget build(BuildContext context) {   return Scaffold(     body: Center(  child: FutureBuilder(  future: _getDataFromServer(widget.num_or),  builder: (context, snapshot) {  if (snapshot.connectionState == ConnectionState.waiting) {  return Center(child: Text('loading...'));  } else {  if (snapshot.hasError)  return Center(child: Text('Error: ${snapshot.error}'));  else  return Center(child: new Text('${snapshot.data}'));  }  },  ),  ),  );   }   

Выход:

 data = [{id:10, name: Imad, number: 1344,origin: OR00348}]  

И, я получаю :

 he method '[]' was called on null. Receiver: null Tried calling: [](0)  

Комментарии:

1. Попробуй перезвонить Future builder или StreamBuilder .

Ответ №1:

Пожалуйста, следуйте приведенному ниже коду

 FutureBuilder(  future: _getDataFromServer(widget.num_or),  builder: (context, snapshot) {  if (snapshot.connectionState == ConnectionState.waiting) {  return Center(child: Text('loading...'));  } else {  if (snapshot.hasError)  return Center(child: Text('Error: ${snapshot.error}'));  else  OdooResponse result = snapshot.data;  return Center(child: new Text('${result.records}'));  }  },  )  

И ваш метод кода должен возвращать значение result

 Futurelt;OdooResponsegt;_getDataFromServer(id) async { OdooResponse result;  client.authenticate(email, password, database).then((auth) async {  if (auth.isSuccess) {  result = await client.searchRead('account.invoice', [  ['id', '=', id]  ], [  'id',  'name',  'number',  'origin'  ]);  var dt = result.getResult();  print("i'm dt $dt");  print("i'm id: $id");  return result.getResult();  } else {  print("Login Gagal");  return result;  }  }); }  

Комментарии:

1. Спасибо за ваш ответ, но у меня есть null ,

2.Спасибо за ваш ответ, но у меня есть null , И когда я пытаюсь отладить его, распечатав повторное задание в будущих значениях initstate; @override void initState() { super.initState(); values = getDataFromServer(widget.num_or); print('im values $values'); } i get im values Instance of 'Futurelt;dynamicgt;'

3. пожалуйста, ознакомьтесь с обновленным ответом

4. та же ошибка Instance of 'Futurelt;dynamicgt;'

5. измените тип возврата Futurelt;OdooResponsegt; с Futurelt;dynamicgt;