如何在SQLITE数据库中创建编辑函数

发布于 2025-02-03 09:51:47 字数 21104 浏览 7 评论 0原文

我创建了一个应用程序,公司可以在其中添加客户的联系方式。数据保存在sqlite上。它与做应用非常相似。在ListTile上,您将获得一个位置图标(尚未功能性),该公司的名称,然后是删除图标(效果很好)。添加按钮正常工作,所有新公司都列出了,并列出了公司的详细信息。

单击公司名称打开瓷砖后,您会看到所有公司的详细信息,但是,在底部,我有一个编辑图标。我似乎找不到我的编辑功能工作。

我找到了一些帮助代码,但是它不起作用,而且由于我对编程的新手,所以我只是不明白我在做什么错。当我单击编辑图标时,它将打开输入页面,其中通常会插入新的详细信息(请参见下文)。它应该做的是打开输入页面,但使用现有的公司详细信息,以便可以进行编辑。

这是我的代码:

我将我的SQFILTE代码保留在我的A库页面:

library

import 'package:sqflite/sqflite.dart';
 import 'package:path/path.dart';

 //Customer

 class Todo {
 int? id;
 final String title;
 final String name;
 final String phone;
 final String fax;
 final String email;
 final String street;
 final String city;
 final String town;
 final String code;
 bool isExpanded;

 Todo({
 this.id,
  required this.title,
  required this.name,
  required this.phone,
  required this.fax,
  required this.email,
  required this.street,
  required this.city,
  required this.town,
  required this.code,
  this.isExpanded = false,
  });

 Map<String, dynamic> toMap() {
 return {
  'id': id,
  'title': title,
  'name': name,
  'phone': phone,
  'fax': fax,
  'email': email,
  'street': street,
  'city': city,
  'town': town,
  'code': code,
  'isExpanded': isExpanded ? 1 : 0,
   };
   }

   @override
   String toString() {
   return 'Todo(id : $id, title : $title, name : $name, phone : $phone, fax: $fax, email: 
   $email, street: $street, city: $city, town: $town, code: $code, isExpanded : 
   $isExpanded,)';
   }
   }




    class DatabaseConnect {
    Database? _database;  
    Future<Database> get database async {    
   final dbpath = await getDatabasesPath();   
   const dbname = 'todo.db';   
   final path = join(dbpath, dbname);   
   _database = await openDatabase(path, version: 1, onCreate: _createDB);

   return _database!;
    }


   Future<void> _createDB(Database db, int version) async {
   await db.execute('''
   CREATE TABLE todo(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT,
    name TEXT,
    phone TEXT,
    fax TEXT,
    email TEXT,
    street TEXT,
    city TEXT,
    town TEXT,
    code TEXT,
    isExpanded INTEGER
  
      )
     ''');
   }


   Future<void> insertTodo(Todo todo) async {   
    final db = await database;   
    await db.insert(
    'todo',
    todo.toMap(),
    conflictAlgorithm: ConflictAlgorithm.replace,
    );
    }

  Future<void> deleteTodo(Todo todo) async {
   final db = await database;
   await db.delete(
  'todo',
  where: 'id == ?',
  whereArgs: [todo.id],
  );
   }

   Future<void> updateTodo(Todo todo) async {
   final db = await database;
   db.update('todo', todo.toMap(), where: 'id=?', whereArgs: [todo.id]);

  }



   Future<List<Todo>> getTodo() async {
   final db = await database;


   List<Map<String, dynamic>> items = await db.query(
  'todo',
  orderBy: 'title ASC',
   ); //this will order the list by id in descending order

  return List.generate(
  items.length,
  (i) => Todo(
    id: items[i]['id'],
    title: items[i]['title'],
    name: items[i]['name'],
    phone: items[i]['phone'],
    fax: items[i]['fax'],
    email: items[i]['email'],
    street: items[i]['street'],
    city: items[i]['city'],
    town: items[i]['town'],
    code: items[i]['code'],
    isExpanded: items[i]['isExpanded'] == 1 ? true : false,
    ),
   );
   }

  Future<List<Todo>> searchContacts(String keyword) async {
  final db = await database;
  List<Map<String, dynamic>> items =
    await db.query('todo', where: 'title LIKE ?', whereArgs: ['$keyword%']);

   return List.generate(
   items.length,
   (i) => Todo(
    id: items[i]['id'],
    title: items[i]['title'],
    name: items[i]['name'],
    phone: items[i]['phone'],
    fax: items[i]['fax'],
    email: items[i]['email'],
    street: items[i]['street'],
    city: items[i]['city'],
    town: items[i]['town'],
    code: items[i]['code'],
    isExpanded: items[i]['isExpanded'] == 1 ? true : false,
    ),
    );
    }
    }

然后,在下面的代码上(casturecercard)在哪里所有新公司数据的ListTile都将转换为卡。在这里还可以看到编辑图标,该图标将被压制到编辑页面。我现在在这里遇到错误,因为我不知道使用“ UpdateFunction”在此处插入什么代码。

customercard

 import 'package:flutter/material.dart';
 import 'library.dart';
 import 'package:test_sqlite/editpage.dart';

 class CustomerCard extends StatefulWidget {
 final int id;
 final String title;
 final String name;
 final String phone;
 final String fax;
 final String email;
 final String street;
 final String city;
  final String town;
  final String code;
  bool isExpanded;
  final Function insertFunction;
  final Function deleteFunction;
  final Function updateFunction;

  CustomerCard(
  {required this.id,
  required this.title,
  required this.name,
  required this.phone,
  required this.fax,
  required this.email,
  required this.street,
  required this.city,
  required this.town,
  required this.code,
  required this.isExpanded,
  required this.insertFunction,
  required this.deleteFunction,
   required this.updateFunction,
  Key? key})
  : super(key: key);

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

  class _CustomerCardState extends State<CustomerCard> {
  var db = DatabaseConnect();

  @override
  Widget build(BuildContext context) {
  var anotherTodo = Todo(
    id: widget.id,
    title: widget.title,
    name: widget.name,
    phone: widget.phone,
    fax: widget.fax,
    email: widget.email,
    street: widget.street,
    city: widget.city,
    town: widget.town,
    code: widget.code,
    isExpanded: widget.isExpanded);

   return Card(
    child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      Theme(
        data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
        child: ExpansionTile(
          initiallyExpanded: false,
          title: Text(
            widget.title,
            style: const TextStyle(
              //fontWeight: FontWeight.bold,
              fontSize: 16,
            ),
          ),
          children: [
            ListTile(
              leading: const Icon(
                Icons.person,
                size: 20,
                color: Colors.teal,
              ),
              visualDensity: const VisualDensity(vertical: -3),
              title: Text(
                widget.name,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.black,
                ),
              ),
            ),
            ListTile(
              leading: const Icon(
                Icons.phone,
                size: 20,
                color: Colors.teal,
              ),
              visualDensity: const VisualDensity(vertical: -4),
              title: Text(
                widget.phone,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.black,
                ),
              ),
            ),
            ListTile(
              leading: const Icon(
                Icons.report,
                size: 20,
                color: Colors.teal,
              ),
              visualDensity: const VisualDensity(vertical: -4),
              title: Text(
                widget.fax,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.black,
                ),
              ),
            ),
            ListTile(
              leading: const Icon(
                Icons.email,
                size: 20,
                color: Colors.teal,
              ),
              visualDensity: const VisualDensity(vertical: -4),
              title: Text(
                widget.email,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.black,
                ),
              ),
            ),
            ListTile(
              leading: const Icon(
                Icons.place,
                size: 20,
                color: Colors.teal,
              ),
              visualDensity: const VisualDensity(vertical: -4),
              title: Text(
                widget.street,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.black,
                ),
              ),
            ),
            ListTile(
              leading: const Icon(
                Icons.place,
                size: 20,
                color: Colors.teal,
              ),
              visualDensity: const VisualDensity(vertical: -4),
              title: Text(
                widget.city,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.black,
                ),
              ),
            ),
            ListTile(
              leading: const Icon(
                Icons.place,
                size: 20,
                color: Colors.teal,
              ),
              visualDensity: const VisualDensity(vertical: -4),
              title: Text(
                widget.town,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.black,
                ),
              ),
            ),
            ListTile(
              leading: const Icon(
                Icons.code,
                size: 20,
                color: Colors.teal,
              ),
              visualDensity: const VisualDensity(vertical: -4),
              title: Text(
                widget.code,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.black,
                ),
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: ElevatedButton(
                    onPressed: () {
                      showModalBottomSheet(
                        isScrollControlled: true,
                        context: context,
                        builder: (context) =>
                            EditPage(updateFunction: addItem),);
                    },
                    style: ElevatedButton.styleFrom(
                      shape: const StadiumBorder(),
                      primary: Colors.white,
                      elevation: 0,
                      padding: const EdgeInsets.symmetric(
                          horizontal: 2, vertical: 2),
                    ),
                    child: const Icon(
                      Icons.edit,
                      size: 20,
                      color: Colors.grey,
                    ),
                  ),
                ),
              ],
            ),
          ],
          leading: const IconButton(
            icon: Icon(
              Icons.place,
              color: Colors.blue,
              size: 20,
            ),
            onPressed: null,
            alignment: Alignment.center,
          ),
          trailing: IconButton(
            onPressed: () {
              widget.deleteFunction(anotherTodo);
            },
            icon: const Icon(
              Icons.delete,
              color: Colors.red,
              size: 20,
            ),

然后编辑页面是输入页面时,在按下编辑按钮时将转到该页面。在此页面上,应该查看所有现有的公司数据,以便可以对其进行编辑,但是它仅打开带有提示文本的新输入页面。

editPage

import 'package:flutter/material.dart';
import 'library.dart';
import 'package:flutter/cupertino.dart';

class EditPage extends StatelessWidget {

final textController = TextEditingController();
final nameController = TextEditingController();
final phoneController = TextEditingController();
final faxController = TextEditingController();
final emailController = TextEditingController();
final streetController = TextEditingController();
final cityController = TextEditingController();
final townController = TextEditingController();
final codeController = TextEditingController();

final Function updateFunction;

 // DatabaseConnect updateFunction = DatabaseConnect();

 EditPage({required this.updateFunction, Key? key, todo}) : super(key: key);

 @override
 Widget build(BuildContext context) {
 return Container(
  padding: const EdgeInsets.all(30.0),
  decoration: const BoxDecoration(
    color: Colors.white,
    borderRadius: BorderRadius.only(
      topLeft: Radius.circular(30.0),
      topRight: Radius.circular(30.0),
    ),
    ),
    child: Scaffold(
     appBar: AppBar(
      backgroundColor: Colors.white,
      elevation: 0,
      title: const Padding(
        padding: EdgeInsets.all(15.0),
        child: Text(
          'Client Details',
          style: TextStyle(color: Colors.black, fontSize: 24),
        ),
      ),
      leading: GestureDetector(
        onTap: () {
          Navigator.of(context).pushReplacementNamed('/homePage');
        },
        child: const Icon(
          Icons.arrow_back,
          color: Colors.black,
        ),
        ),
      ),
      body: SingleChildScrollView(
       child: Container(
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            
              TextField(
              controller: textController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: ' Company Name',
                hintStyle: TextStyle(color: Colors.grey),
              ),
             ),
            TextField(
              controller: nameController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: ' Contact Name & Surname',
                hintStyle: TextStyle(color: Colors.grey),
              ),
            ),
            TextField(
              controller: phoneController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: ' Contact Number',
                hintStyle: TextStyle(color: Colors.grey),
              ),
            ),
            TextField(
              controller: faxController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: 'Fax Number',
                hintStyle: TextStyle(color: Colors.grey),
              ),
            ),
            TextField(
              controller: emailController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: 'Email Address',
                hintStyle: TextStyle(color: Colors.grey),
              ),
            ),
            TextField(
              controller: streetController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: 'Street Name',
                hintStyle: TextStyle(color: Colors.grey),
              ),
            ),
            TextField(
              controller: cityController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: ' City',
                hintStyle: TextStyle(color: Colors.grey),
              ),
            ),
            TextField(
              controller: townController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: 'Town',
                hintStyle: TextStyle(color: Colors.grey),
              ),
            ),
            TextField(
              controller: codeController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: ' Code',
                hintStyle: TextStyle(color: Colors.grey),
              ),
            ),
            GestureDetector(
              onTap: () {
                Navigator.pop(context);
                var myTodo = Todo(
                    title: textController.text,
                    name: nameController.text,
                    phone: phoneController.text,
                    fax: faxController.text,
                    email: emailController.text,
                    street: streetController.text,
                    city: cityController.text,
                    town: townController.text,
                    code: codeController.text,
                    isExpanded: false);
                updateFunction.updateTodo(myTodo);
              },
              child: Padding(
                padding: const EdgeInsets.fromLTRB(0, 10, 0, 0),
                child: Container(
                  decoration: BoxDecoration(
                    color: Theme.of(context).primaryColor,
                    borderRadius: BorderRadius.circular(15),
                  ),
                  padding: const EdgeInsets.symmetric(
                      horizontal: 25, vertical: 10),
                  child: const Text(
                    'Add',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
          

然后,我有一个客户页面,您将在其中看到以下功能:addItem,deleteItem和updateEtem,本质上包含在'insertfunction,deletefunction和updateFunction中。

客户

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import '../customerlist.dart';
import '../library.dart';
import '../user_input.dart';

class Customer extends StatefulWidget {
const Customer({Key? key}) : super(key: key);

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

  class _CustomerState extends State<Customer> {
   var db = DatabaseConnect();

  void addItem(Todo todo) async {
  await db.insertTodo(todo);
  setState(() {});
  }

   void deleteItem(Todo todo) async {
    await db.deleteTodo(todo);
    setState(() {});
    }

    void updateItem(Todo todo) async {
    await db.updateTodo(todo);
    setState(() {});
    }

    @override
     Widget build(BuildContext context) {
     return Scaffold(
      backgroundColor: Colors.white,
     appBar: AppBar(
      centerTitle: false,
      title: const Padding(
        padding: EdgeInsets.all(50.0),
        child: Text(
          'My Clients',
          style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.w600,
              color: Colors.black),
        ),
      ),
      backgroundColor: Colors.white,
      elevation: 0,
      actions: [
        IconButton(
          onPressed: () {
            Navigator.of(context).pushReplacementNamed('/searchPage');
          },
          icon: const Icon(
            Icons.search,
            color: Colors.black,
          ),
        ),
        ]),
        body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
       const Padding(
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
        child: Text(
          'Company Name',
          style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
        ),
        ),
        CustomerList(
         insertFunction: addItem,
          deleteFunction: deleteItem,
         updateFunction: updateItem,
        ),
        ],

    
        ),
       floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.lightBlueAccent,
        child: const Icon(Icons.add),
        onPressed: () {
         showModalBottomSheet(
          isScrollControlled: true,
          context: context,
          builder: (context) => CustomerProfile(insertFunction: addItem),
          );
        }

ps:我真的需要帮助。我已经被困在这里一个多月了。我已经观看了YouTube频道,阅读堆栈溢出和文档,但我根本无法弄清楚。任何帮助真的将不胜感激。

enter image description hereI have created an app where a company can add the contact details of its customers. The data is saved on Sqlite. It is very similar to a To Do app. On the ListTile you get a location icon (not functional yet), the name of the company, then a delete icon (which works fine).The add button works fine and all new companies are listed fine and the details of the company.

enter image description here

Once you click on a company name to open the tile, you see all the company details, BUT, at the bottom I have an Edit icon. I just cannot seem to find my edit functionality to work.

enter image description here

I have found some helping code, but it does not work and as I am fairly new to programming I just don't understand what I am doing wrong. When I click my edit icon, it opens the input page where one would normally insert new details (see below). What it is supposed to do is to open the input page, but with the existing company details so that it can be edited.

enter image description here

Here is my code:

I keep my Sqfilte code in my a Library page:

Library

import 'package:sqflite/sqflite.dart';
 import 'package:path/path.dart';

 //Customer

 class Todo {
 int? id;
 final String title;
 final String name;
 final String phone;
 final String fax;
 final String email;
 final String street;
 final String city;
 final String town;
 final String code;
 bool isExpanded;

 Todo({
 this.id,
  required this.title,
  required this.name,
  required this.phone,
  required this.fax,
  required this.email,
  required this.street,
  required this.city,
  required this.town,
  required this.code,
  this.isExpanded = false,
  });

 Map<String, dynamic> toMap() {
 return {
  'id': id,
  'title': title,
  'name': name,
  'phone': phone,
  'fax': fax,
  'email': email,
  'street': street,
  'city': city,
  'town': town,
  'code': code,
  'isExpanded': isExpanded ? 1 : 0,
   };
   }

   @override
   String toString() {
   return 'Todo(id : $id, title : $title, name : $name, phone : $phone, fax: $fax, email: 
   $email, street: $street, city: $city, town: $town, code: $code, isExpanded : 
   $isExpanded,)';
   }
   }




    class DatabaseConnect {
    Database? _database;  
    Future<Database> get database async {    
   final dbpath = await getDatabasesPath();   
   const dbname = 'todo.db';   
   final path = join(dbpath, dbname);   
   _database = await openDatabase(path, version: 1, onCreate: _createDB);

   return _database!;
    }


   Future<void> _createDB(Database db, int version) async {
   await db.execute('''
   CREATE TABLE todo(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT,
    name TEXT,
    phone TEXT,
    fax TEXT,
    email TEXT,
    street TEXT,
    city TEXT,
    town TEXT,
    code TEXT,
    isExpanded INTEGER
  
      )
     ''');
   }


   Future<void> insertTodo(Todo todo) async {   
    final db = await database;   
    await db.insert(
    'todo',
    todo.toMap(),
    conflictAlgorithm: ConflictAlgorithm.replace,
    );
    }

  Future<void> deleteTodo(Todo todo) async {
   final db = await database;
   await db.delete(
  'todo',
  where: 'id == ?',
  whereArgs: [todo.id],
  );
   }

   Future<void> updateTodo(Todo todo) async {
   final db = await database;
   db.update('todo', todo.toMap(), where: 'id=?', whereArgs: [todo.id]);

  }



   Future<List<Todo>> getTodo() async {
   final db = await database;


   List<Map<String, dynamic>> items = await db.query(
  'todo',
  orderBy: 'title ASC',
   ); //this will order the list by id in descending order

  return List.generate(
  items.length,
  (i) => Todo(
    id: items[i]['id'],
    title: items[i]['title'],
    name: items[i]['name'],
    phone: items[i]['phone'],
    fax: items[i]['fax'],
    email: items[i]['email'],
    street: items[i]['street'],
    city: items[i]['city'],
    town: items[i]['town'],
    code: items[i]['code'],
    isExpanded: items[i]['isExpanded'] == 1 ? true : false,
    ),
   );
   }

  Future<List<Todo>> searchContacts(String keyword) async {
  final db = await database;
  List<Map<String, dynamic>> items =
    await db.query('todo', where: 'title LIKE ?', whereArgs: ['$keyword%']);

   return List.generate(
   items.length,
   (i) => Todo(
    id: items[i]['id'],
    title: items[i]['title'],
    name: items[i]['name'],
    phone: items[i]['phone'],
    fax: items[i]['fax'],
    email: items[i]['email'],
    street: items[i]['street'],
    city: items[i]['city'],
    town: items[i]['town'],
    code: items[i]['code'],
    isExpanded: items[i]['isExpanded'] == 1 ? true : false,
    ),
    );
    }
    }

Then, on the code below (customercard) is where the ListTile with all the new company data is converted into a card. The edit icon is also seen here which onpressed will go to Edit Page. I am now having a error here as I don't know what code to insert here with the 'updateFunction'.

customercard

 import 'package:flutter/material.dart';
 import 'library.dart';
 import 'package:test_sqlite/editpage.dart';

 class CustomerCard extends StatefulWidget {
 final int id;
 final String title;
 final String name;
 final String phone;
 final String fax;
 final String email;
 final String street;
 final String city;
  final String town;
  final String code;
  bool isExpanded;
  final Function insertFunction;
  final Function deleteFunction;
  final Function updateFunction;

  CustomerCard(
  {required this.id,
  required this.title,
  required this.name,
  required this.phone,
  required this.fax,
  required this.email,
  required this.street,
  required this.city,
  required this.town,
  required this.code,
  required this.isExpanded,
  required this.insertFunction,
  required this.deleteFunction,
   required this.updateFunction,
  Key? key})
  : super(key: key);

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

  class _CustomerCardState extends State<CustomerCard> {
  var db = DatabaseConnect();

  @override
  Widget build(BuildContext context) {
  var anotherTodo = Todo(
    id: widget.id,
    title: widget.title,
    name: widget.name,
    phone: widget.phone,
    fax: widget.fax,
    email: widget.email,
    street: widget.street,
    city: widget.city,
    town: widget.town,
    code: widget.code,
    isExpanded: widget.isExpanded);

   return Card(
    child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      Theme(
        data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
        child: ExpansionTile(
          initiallyExpanded: false,
          title: Text(
            widget.title,
            style: const TextStyle(
              //fontWeight: FontWeight.bold,
              fontSize: 16,
            ),
          ),
          children: [
            ListTile(
              leading: const Icon(
                Icons.person,
                size: 20,
                color: Colors.teal,
              ),
              visualDensity: const VisualDensity(vertical: -3),
              title: Text(
                widget.name,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.black,
                ),
              ),
            ),
            ListTile(
              leading: const Icon(
                Icons.phone,
                size: 20,
                color: Colors.teal,
              ),
              visualDensity: const VisualDensity(vertical: -4),
              title: Text(
                widget.phone,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.black,
                ),
              ),
            ),
            ListTile(
              leading: const Icon(
                Icons.report,
                size: 20,
                color: Colors.teal,
              ),
              visualDensity: const VisualDensity(vertical: -4),
              title: Text(
                widget.fax,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.black,
                ),
              ),
            ),
            ListTile(
              leading: const Icon(
                Icons.email,
                size: 20,
                color: Colors.teal,
              ),
              visualDensity: const VisualDensity(vertical: -4),
              title: Text(
                widget.email,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.black,
                ),
              ),
            ),
            ListTile(
              leading: const Icon(
                Icons.place,
                size: 20,
                color: Colors.teal,
              ),
              visualDensity: const VisualDensity(vertical: -4),
              title: Text(
                widget.street,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.black,
                ),
              ),
            ),
            ListTile(
              leading: const Icon(
                Icons.place,
                size: 20,
                color: Colors.teal,
              ),
              visualDensity: const VisualDensity(vertical: -4),
              title: Text(
                widget.city,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.black,
                ),
              ),
            ),
            ListTile(
              leading: const Icon(
                Icons.place,
                size: 20,
                color: Colors.teal,
              ),
              visualDensity: const VisualDensity(vertical: -4),
              title: Text(
                widget.town,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.black,
                ),
              ),
            ),
            ListTile(
              leading: const Icon(
                Icons.code,
                size: 20,
                color: Colors.teal,
              ),
              visualDensity: const VisualDensity(vertical: -4),
              title: Text(
                widget.code,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                  color: Colors.black,
                ),
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: ElevatedButton(
                    onPressed: () {
                      showModalBottomSheet(
                        isScrollControlled: true,
                        context: context,
                        builder: (context) =>
                            EditPage(updateFunction: addItem),);
                    },
                    style: ElevatedButton.styleFrom(
                      shape: const StadiumBorder(),
                      primary: Colors.white,
                      elevation: 0,
                      padding: const EdgeInsets.symmetric(
                          horizontal: 2, vertical: 2),
                    ),
                    child: const Icon(
                      Icons.edit,
                      size: 20,
                      color: Colors.grey,
                    ),
                  ),
                ),
              ],
            ),
          ],
          leading: const IconButton(
            icon: Icon(
              Icons.place,
              color: Colors.blue,
              size: 20,
            ),
            onPressed: null,
            alignment: Alignment.center,
          ),
          trailing: IconButton(
            onPressed: () {
              widget.deleteFunction(anotherTodo);
            },
            icon: const Icon(
              Icons.delete,
              color: Colors.red,
              size: 20,
            ),

Then the editpage which is the input page where one goes to when pressing the edit button. On this page one should see all the existing company data so one can edit it, but it only opens a new input page with hint text.

editpage

import 'package:flutter/material.dart';
import 'library.dart';
import 'package:flutter/cupertino.dart';

class EditPage extends StatelessWidget {

final textController = TextEditingController();
final nameController = TextEditingController();
final phoneController = TextEditingController();
final faxController = TextEditingController();
final emailController = TextEditingController();
final streetController = TextEditingController();
final cityController = TextEditingController();
final townController = TextEditingController();
final codeController = TextEditingController();

final Function updateFunction;

 // DatabaseConnect updateFunction = DatabaseConnect();

 EditPage({required this.updateFunction, Key? key, todo}) : super(key: key);

 @override
 Widget build(BuildContext context) {
 return Container(
  padding: const EdgeInsets.all(30.0),
  decoration: const BoxDecoration(
    color: Colors.white,
    borderRadius: BorderRadius.only(
      topLeft: Radius.circular(30.0),
      topRight: Radius.circular(30.0),
    ),
    ),
    child: Scaffold(
     appBar: AppBar(
      backgroundColor: Colors.white,
      elevation: 0,
      title: const Padding(
        padding: EdgeInsets.all(15.0),
        child: Text(
          'Client Details',
          style: TextStyle(color: Colors.black, fontSize: 24),
        ),
      ),
      leading: GestureDetector(
        onTap: () {
          Navigator.of(context).pushReplacementNamed('/homePage');
        },
        child: const Icon(
          Icons.arrow_back,
          color: Colors.black,
        ),
        ),
      ),
      body: SingleChildScrollView(
       child: Container(
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            
              TextField(
              controller: textController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: ' Company Name',
                hintStyle: TextStyle(color: Colors.grey),
              ),
             ),
            TextField(
              controller: nameController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: ' Contact Name & Surname',
                hintStyle: TextStyle(color: Colors.grey),
              ),
            ),
            TextField(
              controller: phoneController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: ' Contact Number',
                hintStyle: TextStyle(color: Colors.grey),
              ),
            ),
            TextField(
              controller: faxController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: 'Fax Number',
                hintStyle: TextStyle(color: Colors.grey),
              ),
            ),
            TextField(
              controller: emailController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: 'Email Address',
                hintStyle: TextStyle(color: Colors.grey),
              ),
            ),
            TextField(
              controller: streetController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: 'Street Name',
                hintStyle: TextStyle(color: Colors.grey),
              ),
            ),
            TextField(
              controller: cityController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: ' City',
                hintStyle: TextStyle(color: Colors.grey),
              ),
            ),
            TextField(
              controller: townController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: 'Town',
                hintStyle: TextStyle(color: Colors.grey),
              ),
            ),
            TextField(
              controller: codeController,
              autofocus: true,
              textAlign: TextAlign.left,
              decoration: const InputDecoration(
                hintText: ' Code',
                hintStyle: TextStyle(color: Colors.grey),
              ),
            ),
            GestureDetector(
              onTap: () {
                Navigator.pop(context);
                var myTodo = Todo(
                    title: textController.text,
                    name: nameController.text,
                    phone: phoneController.text,
                    fax: faxController.text,
                    email: emailController.text,
                    street: streetController.text,
                    city: cityController.text,
                    town: townController.text,
                    code: codeController.text,
                    isExpanded: false);
                updateFunction.updateTodo(myTodo);
              },
              child: Padding(
                padding: const EdgeInsets.fromLTRB(0, 10, 0, 0),
                child: Container(
                  decoration: BoxDecoration(
                    color: Theme.of(context).primaryColor,
                    borderRadius: BorderRadius.circular(15),
                  ),
                  padding: const EdgeInsets.symmetric(
                      horizontal: 25, vertical: 10),
                  child: const Text(
                    'Add',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
          

Then, I have a customer page where you will see the following functions: addItem, deleteItem and updateItem, which in essence is contained in 'insertFunction, deleteFunction and updateFunction.

customer

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import '../customerlist.dart';
import '../library.dart';
import '../user_input.dart';

class Customer extends StatefulWidget {
const Customer({Key? key}) : super(key: key);

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

  class _CustomerState extends State<Customer> {
   var db = DatabaseConnect();

  void addItem(Todo todo) async {
  await db.insertTodo(todo);
  setState(() {});
  }

   void deleteItem(Todo todo) async {
    await db.deleteTodo(todo);
    setState(() {});
    }

    void updateItem(Todo todo) async {
    await db.updateTodo(todo);
    setState(() {});
    }

    @override
     Widget build(BuildContext context) {
     return Scaffold(
      backgroundColor: Colors.white,
     appBar: AppBar(
      centerTitle: false,
      title: const Padding(
        padding: EdgeInsets.all(50.0),
        child: Text(
          'My Clients',
          style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.w600,
              color: Colors.black),
        ),
      ),
      backgroundColor: Colors.white,
      elevation: 0,
      actions: [
        IconButton(
          onPressed: () {
            Navigator.of(context).pushReplacementNamed('/searchPage');
          },
          icon: const Icon(
            Icons.search,
            color: Colors.black,
          ),
        ),
        ]),
        body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
       const Padding(
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
        child: Text(
          'Company Name',
          style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
        ),
        ),
        CustomerList(
         insertFunction: addItem,
          deleteFunction: deleteItem,
         updateFunction: updateItem,
        ),
        ],

    
        ),
       floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.lightBlueAccent,
        child: const Icon(Icons.add),
        onPressed: () {
         showModalBottomSheet(
          isScrollControlled: true,
          context: context,
          builder: (context) => CustomerProfile(insertFunction: addItem),
          );
        }

PS: I really need help. I have been stucked here for more than a month now. I have watch youtube channels, read stack overflow and the document, but I simply can't figure this out. Any help will really be greatly appreciated..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

手心的海 2025-02-10 09:51:48

从您的问题中,我能够理解的是,基本上,您要与当前数据一起填充编辑页面屏幕,然后允许用户对其进行修改(应该如此)。

在CustomerCard屏幕中,您有数据,并且希望能够对其进行修改。最简单的解决方案,我可以看到,只需将此数据传递给您的编辑页面窗口小部件即可。

class EditPage extends StatelessWidget {

final Todo todo; // <- Add this variable

final late TextEditingController textController; // Do this to add initial value to controller  
final late TextEditingController nameController;
// ...  and the rest of the TextEditingControllers

EditPage({required this.updateFunction, Key? key, 
    required this.todo // <- Add this
}) : super(key: key);

@override
void initState() {
    textController = TextEditingController(text: todo.title);
    nameController = TextEditingController(text: todo.name);
    // .. and add the rest of the fields

    super.initState();
}

@override
Widget build(BuildContext context) {
   ...
}

当您调用编辑页面时,您只需将todo传递给它即可。您可以做到这一点:

EditPage(
    updateFunction: addItem,
    todo: anotherTodo, // This is the todo you are creating in the customerCard
)

这将使您的当前数据填充到编辑页面。然后,您可以调用您的更新方法,以使用新值更新此数据。要获取新值,请在文本字段上添加on Changed函数。

另外,您在编辑页面中有一个错误:

GestureDetector(
          onTap: () {
           // Navigator.pop(context); // <- This should be called at the end
            var myTodo = Todo(
                title: textController.text,
                name: nameController.text,
                phone: phoneController.text,
                fax: faxController.text,
                email: emailController.text,
                street: streetController.text,
                city: cityController.text,
                town: townController.text,
                code: codeController.text,
                isExpanded: false);
            updateFunction.updateTodo(myTodo);
            
            Navigator.pop(context); // <- Here
          },

希望这会有所帮助。

What I was able to understand from going through your question is that, basically you want to make the editPage screen be populated with the current data and then allow user to modify it (as it should be).

In the CustomerCard screen you have the data, and you want to be able to modify it. The simplest solution, I can see is to just pass this data to your EditPage widget.

class EditPage extends StatelessWidget {

final Todo todo; // <- Add this variable

final late TextEditingController textController; // Do this to add initial value to controller  
final late TextEditingController nameController;
// ...  and the rest of the TextEditingControllers

EditPage({required this.updateFunction, Key? key, 
    required this.todo // <- Add this
}) : super(key: key);

@override
void initState() {
    textController = TextEditingController(text: todo.title);
    nameController = TextEditingController(text: todo.name);
    // .. and add the rest of the fields

    super.initState();
}

@override
Widget build(BuildContext context) {
   ...
}

And when you call the editPage, you just pass the todo to it. Here's how you can do it:

EditPage(
    updateFunction: addItem,
    todo: anotherTodo, // This is the todo you are creating in the customerCard
)

This will populate your current data to the editPage. Then you can call your update method to update this data with the new values. To get new values add the onChanged function on the TextFields.

Also you have a bug here in the editPage:

GestureDetector(
          onTap: () {
           // Navigator.pop(context); // <- This should be called at the end
            var myTodo = Todo(
                title: textController.text,
                name: nameController.text,
                phone: phoneController.text,
                fax: faxController.text,
                email: emailController.text,
                street: streetController.text,
                city: cityController.text,
                town: townController.text,
                code: codeController.text,
                isExpanded: false);
            updateFunction.updateTodo(myTodo);
            
            Navigator.pop(context); // <- Here
          },

Hope this helps.

以可爱出名 2025-02-10 09:51:48

我最终设法解决了这个问题。

我的UpdateFunction和UpdateItem功能实际上一直很好地工作。我意识到我从未将“ ID”分配给我的变量“ UpdateTodo”。我只有我的textedingcontroller。现在,在我的SQL数据库中,数据库使用“ Where:ID”进行更新,但是由于我没有为文本分配“ ID”,因此每次更新时,我都会有效地返回null。

这是修复之前的getRuedEtector代码的片段,

GestureDetector(
          onTap: () {
            Navigator.pop(context);
            var updateTodo = Todo(
                
                title: textController.text,
                name: nameController.text,
                phone: phoneController.text,
                fax: faxController.text,
                email: emailController.text,
                street: streetController.text,
                city: cityController.text,
                town: townController.text,
                code: codeController.text,
                isExpanded: false);
            nalaFunction(updateTodo);
          },

在修复程序之后,在这里使用相同的代码:

GestureDetector(
          onTap: () {
            Navigator.pop(context);
            var updateTodo = Todo(
                 id: id,
                title: textController.text,
                name: nameController.text,
                phone: phoneController.text,
                fax: faxController.text,
                email: emailController.text,
                street: streetController.text,
                city: cityController.text,
                town: townController.text,
                code: codeController.text,
                isExpanded: false);
            nalaFunction(updateTodo);
          },

以及在customercard类中传递'id'的代码,直到编辑页面:

class CustomerCard extends StatefulWidget {
 final int id;
 final String title;
 final String name;
 final String phone;
 final String fax;
 final String email;
 final String street;
 final String city;
 final String town;
 final String code;
 bool isExpanded;

final Function janFunction;
final Function simbaFunction;

CustomerCard(
 {required this.id,
 required this.title,
 required this.name,
 required this.phone,
 required this.fax,
 required this.email,
 required this.street,
 required this.city,
 required this.town,
 required this.code,
 required this.isExpanded,

和..

 Row(mainAxisAlignment: MainAxisAlignment.end,
  children: [
  Padding(
  padding: const EdgeInsets.all(8.0),
   child: ElevatedButton(
     onPressed: () {
     showModalBottomSheet(
     isScrollControlled: true,
     context: context,
     builder: (context) => EditPage(
      nalaFunction: widget.simbaFunction,
      variable: anotherTodo,
      id: widget.id,
      ),

                    //updateFunction,
                    //),
                  );
                },

并将“ id”传递到编辑页面以便在同一页面上的GestureDetector可以将其与之联系:

class EditPage extends StatelessWidget {
 final Todo variable;
 final Function nalaFunction;
 final int id;

 late final textController = TextEditingController(text: variable.title);
 late final nameController = TextEditingController(text: variable.name);
 late final phoneController = TextEditingController(text: variable.phone);
 late final faxController = TextEditingController(text: variable.fax);
 late final emailController = TextEditingController(text: variable.email);
 late final streetController = TextEditingController(text: variable.street);
 late final cityController = TextEditingController(text: variable.city);
 late final townController = TextEditingController(text: variable.town);
 late final codeController = TextEditingController(text: variable.code);

 EditPage({Key? key,
 required this.nalaFunction,
 required this.variable,
 required this.id,
 }) : super(key: key);

这解决了我的问题,现在我的应用程序现在可以完美更新新的客户数据。

I have managed to finally resolve the problem.

My updateFunction and updateItem function was actually working just fine all along. I realized that I never assigned an 'id' to my variable ' updateTodo'. I only had my TextEditingController. Now, in my Sql Database, the database is updated using 'Where: id', but since I did not assign an 'id' to my text, I effectively returned Null everytime I updated.

Here is the snippet of code for GetureDetector before the fix,

GestureDetector(
          onTap: () {
            Navigator.pop(context);
            var updateTodo = Todo(
                
                title: textController.text,
                name: nameController.text,
                phone: phoneController.text,
                fax: faxController.text,
                email: emailController.text,
                street: streetController.text,
                city: cityController.text,
                town: townController.text,
                code: codeController.text,
                isExpanded: false);
            nalaFunction(updateTodo);
          },

and here the same code after the fix:

GestureDetector(
          onTap: () {
            Navigator.pop(context);
            var updateTodo = Todo(
                 id: id,
                title: textController.text,
                name: nameController.text,
                phone: phoneController.text,
                fax: faxController.text,
                email: emailController.text,
                street: streetController.text,
                city: cityController.text,
                town: townController.text,
                code: codeController.text,
                isExpanded: false);
            nalaFunction(updateTodo);
          },

and the code for passing the 'id' in CustomerCard class through to EditPage:

class CustomerCard extends StatefulWidget {
 final int id;
 final String title;
 final String name;
 final String phone;
 final String fax;
 final String email;
 final String street;
 final String city;
 final String town;
 final String code;
 bool isExpanded;

final Function janFunction;
final Function simbaFunction;

CustomerCard(
 {required this.id,
 required this.title,
 required this.name,
 required this.phone,
 required this.fax,
 required this.email,
 required this.street,
 required this.city,
 required this.town,
 required this.code,
 required this.isExpanded,

and ..

 Row(mainAxisAlignment: MainAxisAlignment.end,
  children: [
  Padding(
  padding: const EdgeInsets.all(8.0),
   child: ElevatedButton(
     onPressed: () {
     showModalBottomSheet(
     isScrollControlled: true,
     context: context,
     builder: (context) => EditPage(
      nalaFunction: widget.simbaFunction,
      variable: anotherTodo,
      id: widget.id,
      ),

                    //updateFunction,
                    //),
                  );
                },

and passing the 'id' through to the EditPage so that it can be reached by the GestureDetector on the same page:

class EditPage extends StatelessWidget {
 final Todo variable;
 final Function nalaFunction;
 final int id;

 late final textController = TextEditingController(text: variable.title);
 late final nameController = TextEditingController(text: variable.name);
 late final phoneController = TextEditingController(text: variable.phone);
 late final faxController = TextEditingController(text: variable.fax);
 late final emailController = TextEditingController(text: variable.email);
 late final streetController = TextEditingController(text: variable.street);
 late final cityController = TextEditingController(text: variable.city);
 late final townController = TextEditingController(text: variable.town);
 late final codeController = TextEditingController(text: variable.code);

 EditPage({Key? key,
 required this.nalaFunction,
 required this.variable,
 required this.id,
 }) : super(key: key);

This resolved my problem and my app now update new customer data perfectly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文