Saya baru di flutter, dan saya mengembangkan aplikasi untuk menyimpan kata sandi (seperti aplikasi CRUD). Kode sedang bekerja, semuanya, tetapi tidak terlalu jelas dan mudah dilihat. Saya tahu kita dapat memotong bagian kode dan memasukkannya ke dalam file lain, menelepon ke dalam kode utama sebagai metode, tetapi saya tidak tahu apa yang harus dilakukan dengan beberapa bagian khusus dari kode, cuz beberapa bagian digunakan di dalam yang lain. Widget.

Agak sulit untuk dijelaskan, tetapi melihat kode mungkin tampak lebih mudah.

Untuk menunjukkan apa yang ingin saya lakukan, lihat bagian FloatingActionButton . Saya membuat modalcreate, yang merupakan file lain dengan instruksi.

ompressed: () => modalcreate (konteks)

Itulah tepatnya yang ingin saya lakukan ketika saya menekan tombol Edit di aplikasi.

OBS: (Saya menandai dia bagian yang ingin saya ubah dengan "-------".)

Ini kodenya: Homepage

import 'dart:convert';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'dialogAddPass.dart';

class HomePage extends StatelessWidget {
  @override
  static String tag = '/home';

  @override
  Widget build(BuildContext context) {
    Firebase.initializeApp();
    var snapshots = FirebaseFirestore.instance
        .collection('senhas')
        .orderBy('data')
        .snapshots();

    return Scaffold(
      backgroundColor: Colors.grey[200],
      body: Stack(
        alignment: AlignmentDirectional.center,
        children: [
          Align(
            alignment: Alignment.topLeft,
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(
                    height: 60,
                  ),
                  Text.rich(
                    TextSpan(
                      children: <TextSpan>[
                        TextSpan(
                          text: 'Bem-vindo(a)',
                          style: TextStyle(
                              fontFamily: 'SanFrancisco',
                              fontSize: 35,
                              fontWeight: FontWeight.w500),
                        ),
                        TextSpan(
                          text: '\nSuas senhas cadastradas',
                          style: TextStyle(
                              fontSize: 20, fontWeight: FontWeight.w300),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          StreamBuilder(
              stream: snapshots,
              builder: (
                BuildContext context,
                AsyncSnapshot<QuerySnapshot> snapshot,
              ) {
                // Mensagem de erro
                if (snapshot.hasError) {
                  return Center(
                      child: Text('Ocorreu um erro: \n${snapshot.error}'));
                }

                // Bolinha carregando enquanto processa os arquivos.
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Center(child: CircularProgressIndicator());
                }

                // Se nenhuma senha for encontrada
                if (snapshot.data.docs.length == 0) {
                  return ColumnNenhumaSenhaEncontrada();
                }

                // Mostrando as senhas
                return Container(
                  margin: const EdgeInsets.only(top: 130),
                  child: Flexible(
                    child: ListView.builder(
                      itemCount: snapshot.data.docs.length,
                      itemBuilder: (BuildContext context, int i) {
                        var doc = snapshot.data.docs[i];
                        var itens = doc.data();
                        print(itens['nomeDaSenha']);

                        return Container(
                          padding: const EdgeInsets.fromLTRB(0, 5, 0, 15),
                          margin: const EdgeInsets.fromLTRB(15, 15, 15, 5),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(15),
                          ),
                          // Layout de cada senha
                          child: ListTile(
                            isThreeLine: true,
                            // ignore: missing_required_param
                            leading: IconButton(icon: Icon(Icons.lock)),
                            title: Text(itens['nomeDaSenha'],
                                style: TextStyle(
                                    fontSize: 25, color: Colors.orange[700])),
                            subtitle: Text("Senha: ${itens['senha']}",
                                style: TextStyle(fontSize: 20)),
                            trailing: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                IconButton(
                                  icon: Icon(
                                    Icons.edit,
                                    size: 30,
                                    color: Colors.yellow[800],
                                  ),
                                  onPressed: () {
                                  // This part i wanna import as another .dart file
-------------------------------------------------------------------------------------------
                                    var form = GlobalKey<FormState>();
                                    var nomeDaSenha = TextEditingController();
                                    var senha = TextEditingController();

                                    nomeDaSenha.text = doc['nomeDaSenha'];
                                    showDialog(
                                        context: context,
                                        builder: (BuildContext context) {
                                          return AlertDialog(
                                            title: Text('Editar senha 📝'),
                                            titleTextStyle: TextStyle(
                                                fontSize: 20,
                                                color: Colors.black,
                                                fontFamily: "SanFrancisco",
                                                fontWeight: FontWeight.w500),
                                            content: Form(
                                              key: form,
                                              child: Container(
                                                // Deixando o Dialog menor
                                                height: MediaQuery.of(context)
                                                        .size
                                                        .height /
                                                    4,
                                                width: MediaQuery.of(context)
                                                    .size
                                                    .width,
                                                child: Column(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.center,
                                                  children: <Widget>[
                                                    Text(
                                                      'Nome da Senha',
                                                      style: TextStyle(
                                                          fontFamily:
                                                              "SanFrancisco",
                                                          fontSize: 20),
                                                    ),
                                                    SizedBox(height: 5),
                                                    TextFormField(
                                                        // Passando os valores para a variavel nomeDaSenha
                                                        controller: nomeDaSenha,
                                                        textInputAction:
                                                            TextInputAction
                                                                .next,
                                                        decoration:
                                                            InputDecoration(
                                                          hintText:
                                                              'Ex: Banco Itaú',
                                                          border:
                                                              OutlineInputBorder(
                                                            borderRadius:
                                                                BorderRadius
                                                                    .circular(
                                                                        15),
                                                          ),
                                                        ),

                                                        // Tornando o campo obrigatório
                                                        validator: (value) {
                                                          if (value
                                                              .trim()
                                                              .isEmpty) {
                                                            return "Preencha este campo";
                                                          }
                                                          return null;
                                                        }),
                                                    SizedBox(height: 15),
                                                    Text(
                                                      'Senha',
                                                      style: TextStyle(
                                                          fontFamily:
                                                              "SanFrancisco",
                                                          fontSize: 20),
                                                    ),
                                                    SizedBox(height: 2),
                                                    TextFormField(
                                                        obscureText: true,
                                                        textInputAction:
                                                            TextInputAction.go,
                                                        // Passando o valor para a variavel senha
                                                        controller: senha,
                                                        decoration:
                                                            InputDecoration(
                                                          hintText: 'Ex: 12345',
                                                          border:
                                                              OutlineInputBorder(
                                                            borderRadius:
                                                                BorderRadius
                                                                    .circular(
                                                                        15),
                                                          ),
                                                        ),
                                                        // Tornando o campo obrigatório
                                                        validator: (value) {
                                                          if (value
                                                              .trim()
                                                              .isEmpty) {
                                                            return "Preencha este campo";
                                                          }
                                                          return null;
                                                        })
                                                  ],
                                                ),
                                              ),
                                            ),

                                            // Botão Cancelar
                                            actions: <Widget>[
                                              Material(
                                                borderRadius:
                                                    BorderRadius.circular(5),
                                                child: MaterialButton(
                                                  minWidth: 10,
                                                  child: Text(
                                                    "Cancelar",
                                                    style:
                                                        TextStyle(fontSize: 15),
                                                  ),
                                                  onPressed: () =>
                                                      Navigator.of(context)
                                                          .pop(),
                                                ),
                                              ),
                                              // Botão Adicionar
                                              Material(
                                                borderRadius:
                                                    BorderRadius.circular(5),
                                                color: Colors.orange,
                                                child: MaterialButton(
                                                  minWidth: 70,
                                                  child: Text(
                                                    "Editar",
                                                    style: TextStyle(
                                                        color: Colors.white,
                                                        fontSize: 15),
                                                  ),
                                                  onPressed: () async {
                                                    if (form.currentState
                                                        .validate()) {
                                                      snapshot.data.docs[i]
                                                          .reference
                                                          .update({
                                                        'nomeDaSenha':
                                                            nomeDaSenha.text
                                                                .trim(),
                                                        'senha':
                                                            senha.text.trim(),
                                                      }).whenComplete(() =>
                                                              Navigator.of(
                                                                      context)
                                                                  .pop());

                                                      Fluttertoast.showToast(
                                                          msg: "Senha Editada!",
                                                          toastLength: Toast
                                                              .LENGTH_SHORT,
                                                          gravity: ToastGravity
                                                              .BOTTOM,
                                                          backgroundColor:
                                                              Colors.green);
                                                    }
                                                  },
                                                ),
                                              ),
                                            ],
                                          );
                                        });
                                  },
                                ),
-------------------------------------------------------------------------------------------
                                IconButton(
                                  icon: Icon(
                                    Icons.delete,
                                    size: 30,
                                    color: Colors.red[300],
                                  ),
                                  onPressed: () {
                                    doc.reference.delete();
                                    Fluttertoast.showToast(
                                        msg: "Senha apagada",
                                        toastLength: Toast.LENGTH_SHORT,
                                        gravity: ToastGravity.BOTTOM,
                                        backgroundColor: Colors.grey[500]);
                                  },
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                );
              }),
        ],
      ),

      // Floating button Adicionar
      floatingActionButton: Padding(
        padding: const EdgeInsets.only(bottom: 15, right: 5),
        child: FloatingActionButton(
          onPressed: () => modalCreate(context),
          tooltip: 'Adicionar',
          child: Icon(
            Icons.add,
            color: Colors.white,
          ),
        ),
      ),
    );
  }
}

class ColumnNenhumaSenhaEncontrada extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // Imagem no_data_found
        Image(
          image: AssetImage('assets/no_data_found.png'),
          height: 300,
        ),
        Container(
          child: Text.rich(
            TextSpan(
              children: <TextSpan>[
                TextSpan(
                    text: 'Oops!\n',
                    style: TextStyle(
                        fontFamily: 'SanFrancisco',
                        fontSize: 35,
                        fontWeight: FontWeight.w500)),
                TextSpan(
                  text: 'Nenhuma senha encontrada',
                  style: TextStyle(
                    fontFamily: 'SanFrancisco',
                    fontSize: 23,
                    fontWeight: FontWeight.w300,
                  ),
                ),
              ],
            ),
            textAlign: TextAlign.center,
          ),
        ),
      ],
    );
  }
}

dialogaddpass (yang saya gunakan untuk membuat floatingActionbutton bekerja)

// Caixa de dialogo para adicionar senhas
import 'dart:convert';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

modalCreate(BuildContext context) {
  var form = GlobalKey<FormState>();

  // Pegando os valores dos campos
  var nomeDaSenha = TextEditingController();
  var senha = TextEditingController();

  showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Adicionar nova senha 📝'),
          titleTextStyle: TextStyle(
              fontSize: 20,
              color: Colors.black,
              fontFamily: "SanFrancisco",
              fontWeight: FontWeight.w500),
          content: Form(
            key: form,
            child: Container(
              // Deixando o Dialog menor
              height: MediaQuery.of(context).size.height / 4,
              width: MediaQuery.of(context).size.width,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    'Nome da Senha',
                    style: TextStyle(fontFamily: "SanFrancisco", fontSize: 20),
                  ),
                  SizedBox(height: 5),
                  TextFormField(
                      // Passando os valores para a variavel nomeDaSenha
                      controller: nomeDaSenha,
                      textInputAction: TextInputAction.next,
                      decoration: InputDecoration(
                        hintText: 'Ex: Banco Itaú',
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(15),
                        ),
                      ),

                      // Tornando o campo obrigatório
                      validator: (value) {
                        if (value.trim().isEmpty) {
                          return "Preencha este campo";
                        }
                        return null;
                      }),
                  SizedBox(height: 15),
                  Text(
                    'Senha',
                    style: TextStyle(fontFamily: "SanFrancisco", fontSize: 20),
                  ),
                  SizedBox(height: 2),
                  TextFormField(
                      obscureText: true,
                      textInputAction: TextInputAction.go,
                      // Passando o valor para a variavel senha
                      controller: senha,
                      decoration: InputDecoration(
                        hintText: 'Ex: 12345',
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(15),
                        ),
                      ),
                      // Tornando o campo obrigatório
                      validator: (value) {
                        if (value.trim().isEmpty) {
                          return "Preencha este campo";
                        }
                        return null;
                      })
                ],
              ),
            ),
          ),

          // Botão Cancelar
          actions: <Widget>[
            Material(
              borderRadius: BorderRadius.circular(5),
              child: MaterialButton(
                minWidth: 10,
                child: Text(
                  "Cancelar",
                  style: TextStyle(fontSize: 15),
                ),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ),
            // Botão Adicionar
            Material(
              borderRadius: BorderRadius.circular(5),
              color: Colors.orange,
              child: MaterialButton(
                minWidth: 70,
                child: Text(
                  "Salvar",
                  style: TextStyle(color: Colors.white, fontSize: 15),
                ),
                onPressed: () async {
                  if (form.currentState.validate()) {
                    await FirebaseFirestore.instance.collection('senhas').add({
                      'nomeDaSenha': nomeDaSenha.text.trim(),
                      'senha': senha.text.trim(),
                      'data': Timestamp.now(),
                    });

                    Navigator.of(context).pop();

                    Fluttertoast.showToast(
                        msg: "Senha adicionada!",
                        toastLength: Toast.LENGTH_SHORT,
                        gravity: ToastGravity.BOTTOM,
                        backgroundColor: Colors.green);
                  }
                },
              ),
            ),
          ],
        );
      });
}

Saya harap saya jelas, jika tidak, beri tahu saya! Terima kasih!

0
Nícolas 5 April 2021, 05:19

1 menjawab

Jawaban Terbaik

Anda dapat melewati teks dan item Textfield dari data snapshot Anda ke dalam fungsi baru:

show_custom_dialog.dart

  showCustomDialog(String text, item) {
    var form = GlobalKey<FormState>();
    var nomeDaSenha = TextEditingController()..text = text;
    var senha = TextEditingController();
    
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
            // ... other lines
            Material(
              borderRadius: BorderRadius.circular(5),
              color: Colors.orange,
              child: MaterialButton(
                minWidth: 70,
                child: Text(
                  "Editar",
                  style: TextStyle(color: Colors.white, fontSize: 15),
                ),
                onPressed: () async {
                  if (form.currentState.validate()) {
                   item.reference.update({ // Use the item here
                      'nomeDaSenha': nomeDaSenha.text.trim(),
                      'senha': senha.text.trim(),
                    }).whenComplete(() => Navigator.of(context).pop());

                   // ... other lines
                  }
                },
              ),
            ),
          ],
        );
      },
    );
  }

Anda dapat meneruskan data dari showDialog() ke luar juga dengan melewati data melalui Navigator.pop(context, [yourData]) di dalam showDialog, lalu await di luar.

Homepage

// ... other lines
trailing: Row(
      mainAxisSize: MainAxisSize.min,
      children: [
           IconButton(
              icon: Icon(
                Icons.edit,
                size: 30,
                color: Colors.yellow[800],
              ),
           onPressed: () async {
                 // This part i wanna import as another .dart file
---------------------------------------------------------------------------------
                 final data = await showCustomDialog(doc['nomeDaSenha'], snapshot.data.docs[i]);
                 // Do something with the data here (such as whether the call to firebase success), or trigger a toast after displaying the Dialog
---------------------------------------------------------------------------------
// ... other lines
0
Bach 5 April 2021, 03:50