【问题标题】:LateInitializationError: Field 'trackList' has not been initializedLateInitializationError:字段“trackList”尚未初始化
【发布时间】:2021-09-03 03:55:07
【问题描述】:

我想从我创建的 api 中读取列表,但每次我试图从 api 中获取我的列表但我不断收到此错误,我不知道为什么?这个年龄好像有错误,但我不知道错误在哪里,如果有人能帮助我,我将不胜感激。

我想从我创建的 api 中读取列表,但每次我试图从 api 中获取我的列表但我不断收到此错误,我不知道为什么?这个年龄好像有错误,但我不知道错误在哪里,如果有人能帮助我,我将不胜感激。

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
   


    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
   
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,

      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);





  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  final ApiService api = ApiService();
  late List<Track> trackList;



  @override
  Widget build(BuildContext context) {
  if(trackList == null) {
      trackList = <Track>[];
    }

    return Scaffold(
      backgroundColor: Color(0xff121219),
      appBar: AppBar(
        backgroundColor: Color(0xff121219),
        actions: [
           IconButton(
          icon: const Icon(Icons.music_note),
          tooltip: 'Increase volume by 10',
          onPressed: () {
              //  Navigator.push(context,
              //                         MaterialPageRoute(builder: (context) {
              //                       return TrackList( track: [],);
              //                     }));
          },
        ),
        ],
        title: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Image(image: AssetImage('assets/logo.png'), fit: BoxFit.cover, width: 170,),
          ],
        ),

      ),
      body: Center(

      //   child: Column(
          
      //  mainAxisAlignment: MainAxisAlignment.center,
      //     children: <Widget>[
      //       Container(
      //         margin: EdgeInsets.only(bottom: 40),
      //         child: Image(image: AssetImage('assets/vinyl.png'), fit: BoxFit.cover, width: 170,)),
      //       SizedBox(height: 20),
      //       Text(
      //         'Please tab on the "+" to add tracks',
      //         style:TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize:14 ),
              
      //       ),
      //     ],
      //   )

   
        child: trackList.length > 0  ? Container(
        child: new Center(
            child: new FutureBuilder(
              future: loadList(),
              builder: (context, snapshot) {
                return trackList.length > 0? new TracksList(tracks: trackList):
                new Center(child:
                new Text('No data found, tap plus button to add!', style: Theme.of(context).textTheme.title));
              },
            )
        ),
      )  :  Column(
          
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(bottom: 40),
              child: Image(image: AssetImage('assets/vinyl.png'), fit: BoxFit.cover, width: 170,)),
            SizedBox(height: 20),
            Text(
              'Please tab on the "+" to add tracks',
              style:TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize:14 ),
              
            ),
          ],
        )
      ),
        
      
      floatingActionButton: FloatingActionButton(
        backgroundColor: Color(0xffDE1534),
        onPressed: () {
                                  Navigator.push(context,
                                      MaterialPageRoute(builder: (context) {
                                    return AddDataWidget();
                                  }));
                                },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
  Future loadList() async {
    Future<List<Track>> futureCases =  api.getTracks();
    futureCases.then((trackList) {
      setState(() {
        this.trackList = trackList;
      });
    });
    return await futureCases;
  }
}


【问题讨论】:

    标签: flutter


    【解决方案1】:

    从您的声明中,迟到的 List trackList 说您的列表不能为空,因此在脚手架返回之前在 build 方法中检查 null 将始终为 false,因为 trackList 不能为 null(dart intellisense 应该告诉您这一点)和一个空列表永远不会被分配,所以 trackList 永远不会被初始化

    解决方案:将变量声明为 List trackList = [];这样,默认情况下它不是空的或 null,您可以在 API 调用完成时重新分配它。当然,去掉build方法中的null检查和赋值,是没有意义的。

    您的方法确实玷污了您正在使用的未来构建器的目的。如果您自己检查未来调用的状态并调用 setState,则无需使用为自动管理期货状态而构建的 futurebuilder

    【讨论】:

      【解决方案2】:

      尝试改变你的变量:

      late List<Track> trackList; to
      
      List<Track> trackList = [];
      

      该错误表明您的 trackList 在 build() 渲染后未初始化

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-27
        • 2021-10-27
        • 2021-12-29
        • 2022-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-31
        相关资源
        最近更新 更多