gpt4 book ai didi

flutter - Flutter:显示单个列表值时出错

转载 作者:行者123 更新时间:2023-12-03 03:31:09 24 4
gpt4 key购买 nike

在Flutter中,我正在从磁盘读取文件,并将列表项显示为列表。使用ListView.builder可以很好地工作,但是使用显示单个值的文本小部件时出现此错误。有人可以帮忙吗?
我得到的错误是在构建MyHomePage(dirty,state:_MyHomePageState#e9932)时引发了以下RangeError:
RangeError(索引):无效值:有效值范围为空:9


import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
import 'dart:async';

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(),
);
}
}

______________________________

WITH List.View.builder

class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
List<String> _names = [];

Future<List<String>> loadNames() async {
List<String> names = [];
await rootBundle.loadString('assets/Stulkur_A.txt').then((q) => {
for (String i in LineSplitter().convert(q)) {names.add(i)}
});
return names;
}

_setup() async {
List<String> names = await loadNames();
setState(() {
_names = names;
});
}

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

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Names'),
),
body: Center(
child: Container(
padding: EdgeInsets.all(15),
child: ListView.builder(
itemCount: _names.length,
itemBuilder: (context, index) {
return Text(_names[index]);
})),
),
);
}
}

_____________________

WITH Text widget

class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
List<String> _names = [];

Future<List<String>> loadNames() async {
List<String> names = [];
await rootBundle.loadString('assets/Stulkur_A.txt').then((q) => {
for (String i in LineSplitter().convert(q)) {names.add(i)}
});
return names;
}

_setup() async {
List<String> names = await loadNames();
setState(() {
_names = names;
});
}

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

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Names'),
),
body: Center(
child: Container(
padding: EdgeInsets.all(15),
child: Text(_names[9]),
),
),
);
}
}

最佳答案

尝试

body: Center(
child: Container(
padding: EdgeInsets.all(15),
child: _names.isEmpty
? CircularProgressIndicator()
: ListView.builder(
itemCount: _names.length,
itemBuilder: (context, index) {
return Text(_names[index]);
},
),
),
),

关于flutter - Flutter:显示单个列表值时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63809009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com