поиск пользователя из базы данных в реальном времени в приложении Flutter - PullRequest
0 голосов
/ 02 августа 2020

Я загрузил файл Excel в базу данных реального времени. Я новичок, и мне это очень удобно. Особенно, если есть необходимость выгрузить данные обратно для обработки в файл Excel. Итак, сложно найти уроки, как настроить панель поиска в приложении. Пожалуйста помоги. Я также буду рад, если вы подскажете, где я могу научиться работать с базами данных для приложений, созданных на языке Dart.

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

class _MyHomePageState extends State<UserDashboard> implements AddUserCallback {
  TextEditingController editingController = TextEditingController();
  bool _anchorToBottom = false;
  FirebaseDatabaseUtil databaseUtil;


  @override
  void initState() {
    super.initState();
    databaseUtil = FirebaseDatabaseUtil();
    databaseUtil.initState();
  }

  @override
  void dispose() {
    super.dispose();
    databaseUtil.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Widget _buildTitle(BuildContext context) {
      return InkWell(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'List of students',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ],
          ),
        ),
      );
    }

    List<Widget> _buildActions() {
      return <Widget>[
        new IconButton(
          icon: const Icon(
            Icons.group_add,
            color: Colors.white,
          ),
          onPressed: () => showEditWidget(null, false),
        ),
      ];
    }

    return new Scaffold(
        appBar:  AppBar(
          title: _buildTitle(context),
          actions: _buildActions(),
          backgroundColor: Colors.deepPurple,
        ),
        body: Container(
          child: Column(children: <Widget>[
            Expanded(
              child: FirebaseAnimatedList(
                key: ValueKey<bool>(_anchorToBottom),
                query: databaseUtil.getUser(),
                reverse: _anchorToBottom,
                sort: _anchorToBottom
                    ? (DataSnapshot a, DataSnapshot b) => b.key.compareTo(a.key)
                    : null,
                itemBuilder: (BuildContext context, DataSnapshot snapshot,
                    Animation<double> animation, int index) {
                  return SizeTransition(
                    sizeFactor: animation,
                    child: showUser(snapshot),
                  );
                },
              ),
            ),
          ]),
        ));
  }

  @override
  void addUser(User user) {
    setState(() {
      databaseUtil.addUser(user);
    });
  }

  @override
  void update(User user) {
    setState(() {
      databaseUtil.updateUser(user);
    });
  }

  Widget showUser(DataSnapshot res) {
    User user = User.fromSnapshot(res);

    var item = Card(
      child: Container(
          child: Center(
            child: Row(
              children: <Widget>[
                CircleAvatar(
                  radius: 30.0,
                  child: Text(getShortName(user)),
                  backgroundColor: const Color(0xFF20283e),
                ),
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.all(10.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          user.name,
                          // set some style to text
                          style: TextStyle(
                              fontSize: 20.0, color: Colors.deepPurple),
                        ),
                        Text(
                          user.club,
                          // set some style to text
                          style: TextStyle(
                              fontSize: 20.0, color: Colors.lightBlueAccent),
                        ),
                      ],
                    ),
                  ),
                ),
                Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    IconButton(
                      icon: const Icon(
                        Icons.edit,
                        color: Colors.deepPurple,
                      ),
                      onPressed: () => showEditWidget(user, true),
                    ),
                    IconButton(
                      icon: const Icon(Icons.delete_forever),
                      color: Colors.deepPurple,
                      onPressed: () => onDelete(user),
                    ),
                  ],
                ),
              ],
            ),
          ),
          padding: const EdgeInsets.fromLTRB(10.0, 0.0, 0.0, 0.0)),
    );

    return item;
  }

  String getShortName(User user) {
    String shortName = "";
    if (!user.name.isNotEmpty) {
      shortName = user.name.substring(0, 1);
    }
    return shortName;
  }

  showEditWidget(User user, bool isEdit) {
    showDialog(
      context: context,
      builder: (BuildContext context) =>
          AddUserDialog().buildAboutDialog(context, this, isEdit, user),
    );
  }

  void onDelete(User user) async {
    if (await _showConfirmationDialog(context)) {
      databaseUtil.deleteUser(user);
    }
  }

  Future<bool> _showConfirmationDialog(BuildContext context) async {
    return showDialog(
        context: context,
        barrierDismissible: true,
        builder: (context) => AlertDialog(
              content: Text("Delete?"),
              actions: <Widget>[
                FlatButton(
                  textColor: Colors.red,
                  child: Text("Delete"),
                  onPressed: () => Navigator.pop(context, true),
                ),
                FlatButton(
                  textColor: Colors.black,
                  child: Text("Cancel"),
                  onPressed: () => Navigator.pop(context, false),
                ),
              ],
            ));
  }
}

Вот как я загружаю и выгружаю данные в приложение:

class FirebaseDatabaseUtil {
  DatabaseReference _counterRef;
  DatabaseReference _userRef;
  StreamSubscription<Event> _counterSubscription;
  StreamSubscription<Event> _messagesSubscription;
  FirebaseDatabase database = FirebaseDatabase();
  int _counter;
  DatabaseError error;

  static final FirebaseDatabaseUtil _instance =
  new FirebaseDatabaseUtil.internal();

  FirebaseDatabaseUtil.internal();

  factory FirebaseDatabaseUtil() {
    return _instance;
  }

  void initState() {
    // Demonstrates configuring to the database using a file
    _counterRef = FirebaseDatabase.instance.reference().child('counter');
    // Demonstrates configuring the database directly



    _userRef = database.reference().child('record');
    database.reference().child('counter').once().then((DataSnapshot snapshot) {
      print('Connected to second database and read ${snapshot.value}');
    });
    database.setPersistenceEnabled(true);
    database.setPersistenceCacheSizeBytes(10000000);
    _counterRef.keepSynced(true);

    _counterSubscription = _counterRef.onValue.listen((Event event) {
      error = null;
      _counter = event.snapshot.value ?? 0;
    }, onError: (Object o) {
      error = o;
    });
  }

  DatabaseError getError() {
    return error;
  }

  int getCounter() {
    return _counter;
  }

  DatabaseReference getUser() {
    return _userRef;
  }

  addUser(User user) async {
    final TransactionResult transactionResult =
    await _counterRef.runTransaction((MutableData mutableData) async {
      mutableData.value = (mutableData.value ?? 0) + 1;

      return mutableData;
    });

    if (transactionResult.committed) {
      _userRef.push().set(<String, String>{
        "Name": "" + user.name,
        "date": "" + user.date,
        "email": "" + user.email,
        "phone": "" + user.phone,
        "Place": "" + user.place,
        "Club": ""  + user.club,
      }).then((_) {
        print('Transaction  committed.');
      });
    } else {
      print('Transaction not committed.');
      if (transactionResult.error != null) {
        print(transactionResult.error.message);
      }
    }
  }

  void deleteUser(User user) async {
    await _userRef.child(user.id).remove().then((_) async{
                await _counterRef.runTransaction((MutableData mutableData) async {
        mutableData.value = (mutableData.value ?? 0) - 1;
        return mutableData;
      });
      print('Transaction  committed.');
    });
  }

  void updateUser(User user) async {
    await _userRef.child(user.id).update({
      "Name": "" + user.name,
      "date": "" + user.date,
      "email": "" + user.email,
      "phone": "" + user.phone,
      "Place": "" + user.place,
      "Club": ""  + user.club,
    }).then((_) {
      print('Transaction  committed.');
    });
  }

  void dispose() {
    _messagesSubscription.cancel();
    _counterSubscription.cancel();
  }
}

Вот информация из RTDB:

Datafetchfrom
  counter: 2
  record
    0
     Club:"Club1"
     Name:"Name1"
     Place:"City1"
     date: "31737"
     email:"sss@gmail.com"
     phone:"98988"
   2
     Club:"Club2"
     Name:"Name2"
     Place:"City2"
     date: "34334"
     email:"ddd@gmail.com"
     phone:"12333"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...