How to display data from stream builder into textfields and update the from listview?

174 views Asked by At

Basically, I want to update my data from listview. when click button edit, it will display data from listview. here is my picture.myhomesupervisor updateSupervisor. I already use many method to display but still got nothing.

This is my code.

Function update.

 // update data supervisor
    Future updateData(NewUser newUser) async {
    return supervisorCollection.document(newUser.id).updateData({
        'name': name,
        'email': email,
        'nophone': nophone,
        'uniqueID': uniqueID,
    });
    }

HomeSupervisor class

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:finalyearproject/model/NewUser.dart';
import 'package:flutter/material.dart';
import 'package:finalyearproject/screen/crud/UpdateSupervisor.dart';
import 'package:finalyearproject/screen/crud/AddSupervisor.dart';
import 'package:finalyearproject/sidebar/AdminDrawer.dart';
import 'package:provider/provider.dart';


NewUser user;

class HomeSupervisor extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.redAccent,
        title: Text('Supervisor'),
        actions: <Widget>[
          IconButton(
              icon: Icon(
                Icons.add,
                color: Colors.white,
              ),
              onPressed: () {
                Navigator.push(context, MaterialPageRoute(builder: (context) => AddSupervisor()));
              })
        ],
      ),
      drawer: AdminDrawer(),
      body: ListSupervisor(),

    );
  }

}

class ListSupervisor extends StatefulWidget {
  @override
  _ListSupervisorState createState() => _ListSupervisorState();
}

class _ListSupervisorState extends State<ListSupervisor> {
  String email;
  String name;
  String nophone;
  String uniqueID;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: StreamBuilder(
          stream: Firestore.instance.collection('Supervisor').snapshots(),
          builder: (_, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: Text("Loading..."),
              );
            } else {
              return ListView.builder(
                  itemCount: snapshot.data.documents.length,
                  itemBuilder: (_, index) {
                    DocumentSnapshot sv = snapshot.data.documents[index];
                    return Card(
                      child: ListTile(
                          title: Container(
                            alignment: Alignment.centerLeft,
                            child: Column(
                              children: <Widget>[
                                SizedBox(height: 5.0),
                                Container(alignment: Alignment.centerLeft,
                                  child: Text(sv['name']),
                                ),

                                SizedBox(height: 5.0),
                                Container(alignment: Alignment.centerLeft,
                                  child: Text(sv['email']),
                                ),
                                SizedBox(height: 5.0),
                                Container(alignment: Alignment.centerLeft,
                                  child: Text(sv['uniqueID']),
                                 )
                              ],
                            ),
                          ),
                          trailing: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: <Widget>[
                              IconButton(
                                  icon: Icon(Icons.delete),
                                  color: Colors.red,
                                  onPressed: (){

                                  }
                              ),
                              IconButton(
                                  icon: Icon(Icons.edit),
                                  color: Colors.black,
                                  onPressed: () {
                                    Navigator.push(context, MaterialPageRoute(builder: (context) => UpdateSupervisor()));
                                  }
                              ),
                              IconButton(
                                  icon: Icon(Icons.share),
                                  onPressed: () {

                                  }
                              ),
                            ],
                          )
                      ),
                    );
                  });
            }
          }),
    );
  }
}

UpdateSupervisor class

import 'package:finalyearproject/model/NewUser.dart';
import 'package:finalyearproject/service/database.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';




class UpdateSupervisor extends StatefulWidget {
  final String name;
  final String email;
  final String uniqueID;
  final String phone;
  UpdateSupervisor({this.name, this.email, this.phone, this.uniqueID});

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

class _UpdateSupervisorState extends State<UpdateSupervisor> {

  TextEditingController _name =  new TextEditingController();
  TextEditingController _email =  new TextEditingController();
  TextEditingController _nophone =  new TextEditingController();
  TextEditingController _uniqueID =  new TextEditingController();
  // form values
  String name;
  String email;
  String uniqueID;
  String phone;


  final GlobalKey<FormState> _formKey = GlobalKey();

  @override
  Widget build(BuildContext context) {

    return Scaffold(
        appBar: AppBar(
          title: Text('Edit Supervisor'),
          backgroundColor: Colors.redAccent,
        ),
             body: Form(
                key: _formKey,
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: <Widget>[
                      SizedBox(height: 25.0),
                      TextFormField(
                        decoration: InputDecoration(
                            hintText: 'Name',
                            border: OutlineInputBorder(borderRadius: BorderRadius.circular(5))),
                        keyboardType: TextInputType.text,
                        controller: _name,
                        validator: (value) => value.isEmpty ? 'Name cannot be empty!': null,
                        onChanged: (value) {
                          setState(() => name = value);
                        },
                      ),
                      SizedBox(height: 10.0),
                      TextFormField(
                        decoration: InputDecoration(
                            hintText: 'Email',
                            border: OutlineInputBorder(borderRadius: BorderRadius.circular(5))),
                        keyboardType: TextInputType.emailAddress,
                        controller: _email,
                        validator: (value) => value.isEmpty ? 'Email cannot be empty!': null,
                        onChanged: (value) {
                          setState(() => email = value);
                        },
                      ),
                      SizedBox(height: 10.0),
                      TextFormField(
                        decoration: InputDecoration(
                            hintText: 'Number Phone',
                            border: OutlineInputBorder(borderRadius: BorderRadius.circular(5))),
                        keyboardType: TextInputType.number,
                        controller: _nophone,
                        validator: (value) => value.isEmpty ? 'Number Phone cannot be empty!': null,
                        onChanged: (value) {
                          setState(() => phone = value);
                        },
                      ),
                      SizedBox(height: 10.0),
                      TextFormField(
                        decoration: InputDecoration(
                            hintText: 'Unique ID ',
                            border: OutlineInputBorder(borderRadius: BorderRadius.circular(5))),
                        keyboardType: TextInputType.number,
                        controller: _uniqueID,
                        validator: (value) => value.isEmpty ? 'Ic number cannot be empty!': null,
                        onChanged: (value) {
                          setState(() => uniqueID = value);
                        },
                      ),
                      const SizedBox(height: 20.0),
                      RaisedButton(
                          color: Colors.redAccent,
                          textColor: Colors.black,
                          child: Text("Update"),
                          onPressed: () async {
                            if(_formKey.currentState.validate()){
                              DatabaseService().updateData(NewUser(name: name, email: email, nophone: phone, uniqueID: uniqueID));
                              _formKey.currentState.save();
                            }
                          }
                      ),
                    ],
                  ),
                ),
                 )
              );

  }
}

I already use StreamBuilder to display data from listview into the textfield but yeah still got nothing. And also using provider but the process are too slow because my case it involve many widget. Then now I want to try the simple method but still got nothing. can someone help me or give me any solution to solve this problem?

1

There are 1 answers

2
John Joe On BEST ANSWER

You need to pass data in this line

 Navigator.push(context, MaterialPageRoute(builder: (context) => UpdateSupervisor(data:sv)));

Then in your UpdateSupervisor:

final DocumentSnapshot sv ;

TodosScreen({Key key, @required this.sv}) : super(key: key);

You can get more info here : Send data to a new screen