【问题标题】:How to call setState in a extended class?如何在扩展类中调用 setState?
【发布时间】:2020-03-17 12:25:48
【问题描述】:
class Cari  extends AnaState implements InterHttp {
  String token = Tokenlar.token();

   Future<Void>  getCariHareket() async {
    final response = await get(
      "http://148.111.156.214:36555/Api/Customers/CustomerActionById/3",
      headers: {HttpHeaders.authorizationHeader: "bearer $token",HttpHeaders.acceptHeader: "application/json"},      
    );

    if (response.statusCode == 200) 
    {
      List<CariHareketListe> hareketListe=(json.decode(response.body) as List).map((i) =>
              CariHareketListe.fromJson(i)).toList();  
      //Map<String,dynamic> map =  json.decode(response.body); 
      setState(() {
        provider = hareketListe;
      });
    } 
    else 
    {
      throw Exception('Cari hareket listesi yükleme başarısız oldu');
    }
  }

}

我希望能够在这个类中调用 setstate,但它给了我这个错误:

FlutterError (setState() 在构造函数中调用:Cari#ed627(生命周期状态:已创建,无小部件,未安装) 当您对尚未插入到小部件树的小部件的 State 对象调用 setState() 时,就会发生这种情况。没有必要在构造函数中调用 setState(),因为在最初创建状态时已经假定状态是脏的。)

这是我想在 cari 中设置状态的主要 dart,然后我希望该数据进入 Icwidgetlar 以便能够将列表视图返回给 Anastate

import 'package:flutter/material.dart';
import 'package:guven_avize/ApiMetodlar/CariMetod.dart';
import 'Veriler/CariVeriler.dart';
class Anamenu 
{
  Anamenu() 
  {

  }
}
class Ana extends StatefulWidget{
  @override
  AnaState createState() => AnaState();
}



class IcWidgetlar  
{
    List<CariHareketListe> provider = new List<CariHareketListe>();

ListView icyapi(int secilenTab)
{

  if (secilenTab == 0) 
  {    
    Cari cari = new Cari();
    cari.veriCek(1);
ListView.builder(
  padding: const EdgeInsets.all(8),
  itemCount: provider.length,
  itemBuilder: (BuildContext context, int index) {
    return Container(
      height: 50,
      color: Colors.amber,
      child: Center(child: Text('Entry ${provider[index]}')),
    );
  }
);
  }
}
}




class AnaState extends State<Ana> with IcWidgetlar {

IcWidgetlar widgetlar = new IcWidgetlar();

int selectedIndex = 0;
 static const TextStyle optionStyle = TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
 static const List<Widget> _widgetOptions = <Widget>[
  Text(
    'Cari',
    style: optionStyle,
  ),
  Text(
     'Stok',
     style: optionStyle,
  ),
  Text(
     'Sipariş',
     style: optionStyle,
  ),
];

void _onItemTapped(int index) {
  setState(() {
    selectedIndex = index;
  });
}
  @override
  Widget build(BuildContext context) {
     return new WillPopScope(
    onWillPop: () async => false,     
child: Scaffold(
   appBar: AppBar(
     automaticallyImplyLeading: false,
     backgroundColor: Color.fromRGBO(106, 112, 222, 50),
      title: _widgetOptions.elementAt(selectedIndex),
    ),  
    body: widgetlar.icyapi(selectedIndex),
    bottomNavigationBar: BottomNavigationBar(      
      items: const <BottomNavigationBarItem>[
        BottomNavigationBarItem(
          icon: Icon(Icons.face),
          title: Text('Cari'),
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.inbox),
          title: Text('Stok'),
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.shopping_cart),
          title: Text('Sipariş'),
        ),
      ],
      currentIndex: selectedIndex,
      selectedItemColor: Colors.amber[800],
      onTap: _onItemTapped,
    ),
  ));
  }
}

【问题讨论】:

    标签: flutter


    【解决方案1】:

    你为什么不返回结果呢?

    返回Future而不是返回Future>,然后从其他类中获取。

    您甚至可以使用 FutureBuilder 等到响应到达。

    在initState中调用函数

          @override
          void initState() {
            super.initState();
            getCariHareket().then( (list) {
                          setState((){
                              provider = list;
                          }())
            });
        }
    

    【讨论】:

    • 给出这个错误“future is not a subtype of List
    • 您应该在调用该函数后使用 .then。我将在几秒钟内编辑我的答案以显示示例
    • 观看此视频,了解有关FutureBuilder的更多信息
    • 对不起,我是新手,我应该把那个方法放在哪里?
    • 状态内部。在你的情况下,在class AnaState extends State&lt;Ana&gt; with IcWidgetlar
    猜你喜欢
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    相关资源
    最近更新 更多