Я создаю приложение ToDo с Flutter. Теперь я добавил анонимный логин, чтобы у каждого устройства были свои задачи. Но все устройства по-прежнему показывают одинаковые задачи. Я пытался добавить .document (user.uid), но это не сработало, потому что «пользователь» стал красным. Итак, как я могу прочитать данные только одного пользователя на этом устройстве? Другая проблема, с которой я сталкиваюсь, состоит в том, что ToDo не добавляет к существующему внутри документа userID в базе данных, иначе он просто обновляет «старый». Это мой код: (Дайте мне знать, если вам нужна другая часть кода)
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String input = "";
createTodos() async{
FirebaseUser user = await FirebaseAuth.instance.currentUser();
DocumentReference documentReference =
Firestore.instance.collection("MyTodos").document(user.uid);
//Map
Map<String, String> todos = {"todoTitle": input};
documentReference.setData(todos).whenComplete(() {
print("$input created");
});
}
deleteTodos(item) {
DocumentReference documentReference =
Firestore.instance.collection("users").document();
documentReference.delete().whenComplete(() {
print("$item deleted");
});
}
moveTodos(item) {
DocumentReference documentReference =
Firestore.instance.collection("users").document(item);
//Map
Map<String, String> todos = {"todoMove": item};
documentReference.setData(todos).whenComplete(() {
print("$input moved");
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
backgroundColor: Colors.grey[300],
title: Text('Add ToDo',
style: TextStyle(fontWeight: FontWeight.bold),),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15)
),
content: TextField(
onChanged: (String value) {
input = value;
},
),
actions: <Widget>[
FlatButton(
onPressed: () {
createTodos();
Navigator.of(context).pop();
},
child: Text('Add'))
],
);
});
},
child: Container(
width: 200,
height: 200,
child: Icon(Icons.add, color: Colors.grey[700],),
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.all(Radius.circular(50)),
boxShadow: [
BoxShadow(
color: Colors.grey[500],
offset: Offset(4.0, 4.0),
blurRadius: 15.0,
spreadRadius: 1.0
),
BoxShadow(
color: Colors.white,
offset: Offset(-4.0, -4.0),
blurRadius: 15.0,
spreadRadius: 1.0
),
]
),
)
),
body: StreamBuilder(
stream: Firestore.instance.collection("users").snapshots(),
builder: (context, snapshots){
if(snapshots.data == null) return CircularProgressIndicator();
return ListView.builder(
shrinkWrap: true,
itemCount: snapshots.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot documentSnapshot = snapshots.data.documents[index];
return Dismissible(
background: Container(
color: Colors.green,
alignment: Alignment(-0.9, 0),
child: Icon(Icons.check, color: Colors.white,),
),
secondaryBackground: Container(
color: Colors.red,
alignment: Alignment(0.9, 0),
child: Icon(Icons.delete, color: Colors.white,),
),
onDismissed: (direction) {
if (direction == DismissDirection.startToEnd) {
moveTodos(documentSnapshot["todoTitle"]);
deleteTodos(documentSnapshot["todoTitle"]);
} else
if (direction == DismissDirection.endToStart) {
deleteTodos(documentSnapshot["todoTitle"]);
}
},
key: Key(documentSnapshot["todoTitle"]),
child: Container(
margin: EdgeInsets.all(8),
child: Card(
margin: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)
),
color: Colors.grey[300],
child: ListTile(
title: Text(documentSnapshot["todoTitle"] ?? "No ToDos yet!"),
trailing: Wrap(
children: <Widget>[
IconButton(
icon: Icon(Icons.check),
color: Colors.green,
onPressed: (){
moveTodos(documentSnapshot["todoTitle"]);
deleteTodos(documentSnapshot["todoTitle"]);
} ),
IconButton(
icon: Icon(Icons.delete),
color: Colors.red,
onPressed: (){
deleteTodos(documentSnapshot["todoTitle"]);
} ),
],
)
),
),
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.all(Radius.circular(10)),
boxShadow: [
BoxShadow(
color: Colors.grey[500],
offset: Offset(4.0, 4.0),
blurRadius: 15.0,
spreadRadius: 1.0
),
BoxShadow(
color: Colors.white,
offset: Offset(-4.0, -4.0),
blurRadius: 15.0,
spreadRadius: 1.0
),
]
),
),
);
});
}),
backgroundColor: Colors.grey[300],
);
}
}