【发布时间】:2020-05-26 06:40:39
【问题描述】:
我对 Flutter 非常陌生,需要帮助来构建我的应用程序。
当我运行项目时,它会报错:RangeError (index): Invalid value: Valid value range is empty: 0,我无法显示除一个以外的任何联系人,并且这甚至不是第一次接触。
请帮忙。谢谢。
我的代码:
import 'dart:io';
import 'package:contacts_service/contacts_service.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.dumpErrorToConsole(details);
if (kReleaseMode)
exit(1);
};
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter contacts',
theme: ThemeData(),
home: MyHomePage(title: 'Contacts Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Contact> contacts = [];
@override
void initState() {
// TODO: implement initState
super.initState();
getAllContacts();
}
getAllContacts() async{
List<Contact> _contacts = (await ContactsService.getContacts()).toList();
setState(() {
contacts = _contacts;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
padding: EdgeInsets.all(20),
child: Column(
children: <Widget>[
Text(
'Phone Book',
),
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: contacts.length,
itemBuilder: (context, index){
Contact contact = contacts[index];
return ListTile(
title: Text(contact.displayName),
subtitle: Text(
contact.phones.elementAt(0).value
),
leading: (contact.avatar != null && contact.avatar.length > 0) ?
CircleAvatar(backgroundImage: MemoryImage(contact.avatar),
):
CircleAvatar(child: Text(contact.initials()),),
);
},
)
)
],
),
),
);
}
}
我拥有所有适当的依赖项,并且还指定了用户权限来读取和写入。
谢谢!!
【问题讨论】:
-
能否添加 ContactsService 类的代码?
标签: flutter android-contacts mobile-application