jamesblasco / modal_bottom_sheet

Flutter | Create advanced modal bottom sheets. Material, Cupertino or your own style
https://pub.dev/packages/modal_bottom_sheet
MIT License
1.86k stars 466 forks source link

Pleas help me Add " Add Cattegorry" Dialog to the Main Grid View screen main.dart with customized names option and predfined images #137

Closed srk2k13 closed 3 years ago

srk2k13 commented 3 years ago

Hi, Pleas help me Add " Add Cattegorry" Dialog to the Main Grid View screen main.dart with customized names option and prdfined images Just like this page.

                  mobiles.dart

import 'package:sqlite_crud_flutter/ShowDetails.dart';

import 'package:sqlite_crud_flutter/models/entry.dart'; import 'package:sqlite_crud_flutter/upload_data.dart';

import 'category.dart'; import 'item.dart'; import 'add_category.dart'; import 'add_item_pages.dart'; import 'item_details.dart'; import 'inventory_custom_icons_icons.dart'; import 'package:flutter/material.dart'; import 'package:hive/hive.dart'; import 'package:path_provider/path_provider.dart'; import 'package:provider/provider.dart'; import 'package:uuid/uuid.dart';

import 'items_model.dart';

void main() async { WidgetsFlutterBinding.ensureInitialized(); final dir = await getApplicationDocumentsDirectory(); Hive.init(dir.path); registerAdapters(); runApp(MyApp()); }

class MyApp extends StatelessWidget { // This widget is the root of your application.

@override Widget build(BuildContext context) {

return MultiProvider(
  providers: [
    ChangeNotifierProvider<ViewModel>(
      create: (context) => ViewModel(),
    )
  ],
  child: MaterialApp(
      debugShowCheckedModeBanner: false,
      initialRoute: '/',
      routes: {
        // When navigating to the "/" route, build the FirstScreen widget.
        '/': (context) => MyHomePage(),

        //home: MyHomePage(),
      }),
);

} }

class MyHomePage extends StatefulWidget { MyHomePage({Key key}) : super(key: key);

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

class _MyHomePageState extends State { ViewModel viewModel; @override void initState() { super.initState(); }

Future _onBackPressed() { return showDialog( context: context, builder: (context) => new AlertDialog( title: new Text('Are you sure?'), content: new Text('Do you want to exit an App'), actions: [ new GestureDetector( onTap: () => Navigator.of(context).pop(false), child: Text("NO"), ), SizedBox(height: 16), new GestureDetector( onTap: () => Navigator.of(context).pop(true), child: Text("YES"), ), ], ), ) ?? false; }

@override Widget build(BuildContext context) { if (viewModel == null) { viewModel = Provider.of(context); viewModel.getAllCategories(); } return WillPopScope( onWillPop: _onBackPressed, child: new Scaffold( appBar: AppBar( centerTitle: true, backgroundColor: Colors.blue, title: new Text("Gadget", style: TextStyle(fontSize: 20), textAlign: TextAlign.center), ),

  body: Center(
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
          maxCrossAxisExtent: 200,
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
          childAspectRatio: 1,
        ),
        itemBuilder: (context, item) {
          return Container(
            child: GestureDetector(
                onTap: () {

                  Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => UploadData()));
                  //Navigate to the Page you have
                 /* Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) => ItemDetailPage(
                        category: viewModel.categories[item],
                      ),
                    ),
                  );*/
                },
                child: Card(
                  elevation: 2,
                  margin: EdgeInsets.all(5.0),
                  //color: Colors.cyan[100],
                  shape: new RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(20.0)),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Icon(
                        getIconData(viewModel.categories[item].iconName),
                        size: 90,
                      ),
                      SizedBox(height: 20),
                      Text(viewModel.categories[item].name,
                          style: TextStyle(
                              color: Colors.blue,
                              fontSize: 14.0,
                              fontWeight: FontWeight.bold),
                          textAlign: TextAlign.center),
                    ],
                  ),
                )),
          );
        },
        itemCount: viewModel.categories.length,
        primary: false,
        padding: const EdgeInsets.all(20),
      )),

  floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
  floatingActionButton: FloatingActionButton(
    backgroundColor: Colors.red,
    mini: false,
    highlightElevation: 20.0,
    //shape: BeveledRectangleBorder(borderRadius:BorderRadius.all(Radius.circular(16.0)) ),
    onPressed: () {
      debugPrint("Add New Device Category");
      Navigator.push(context, MaterialPageRoute(builder: (context) {
        return AddCategory(
          viewModel: viewModel,
        );
      })); //
    },
    tooltip: 'Add Device Cattegorry',
    child: Icon(Icons.add),
  ),

  //
),
);

}

getIconData(String iconName) { try { return iconData[iconData.keys.firstWhere((key) => key == iconName)]; } catch (e) { return Icons.star; } } }

Map<String, IconData> iconData = { "Mobile": Icons.smartphone, "Mobile Accessories" : Icons.headset, "Computers": Icons.computer, "Televisions": Icons.tv, "Large Appliances" : Icons.local_laundry_service, "Kitchen Appliances" :Icons.kitchen, "Home Appliances" : Icons.home, "Home Entertainment Systems" : Icons.devices_other, "Head Phones" : Icons.headset_mic, "Cameras" : Icons.photo_camera, "Speakers" : Icons.speaker, "Camera Accessories" : Icons.camera_roll,

};

class ItemModel { String item; IconData icon; Widget page; ItemModel({this.item, this.icon, this.page}); }

Please integrate the same Add Cattegorry Functionality to the below main screen

                                                                      main.dart

// ignore: unused_import import 'mobileaccessories.dart'; import 'mobiles.dart'; import 'computers.dart'; import 'tv.dart'; import 'largeapp.dart';

import 'kitchenappls.dart'; import 'homeapp.dart'; import 'homentsys.dart'; import 'headphones.dart'; import 'cameras.dart'; import 'speakers.dart'; import 'camaccrs.dart';

import 'items_model.dart';

import 'add_category.dart';

import 'item_details.dart';

import 'package:flutter/material.dart'; import 'package:hive/hive.dart'; import 'package:path_provider/path_provider.dart'; import 'package:provider/provider.dart'; import 'package:uuid/uuid.dart'; import 'package:flutter/services.dart';

void main() async { WidgetsFlutterBinding.ensureInitialized();

final dir = await getApplicationDocumentsDirectory(); Hive.init(dir.path); registerAdapters(); await SystemChrome.setPreferredOrientations( [DeviceOrientation.portraitUp]);// To turn off landscape mode runApp(MyApp()); }

class MyApp extends StatelessWidget { // This widget is the root of your application.

@override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider( create: (context) => ViewModel(), ) ], child: MaterialApp( debugShowCheckedModeBanner: false, initialRoute: '/', routes: { // When navigating to the "/" route, build the FirstScreen widget. '/': (context) => MyHomePage(),

        //home: MyHomePage(),
      }),
);

} }

List items = [ //These will have separate page ItemModel(item: "Mobiles", icon: Icons.smartphone, page: MobilesPage()), ItemModel( item: "Mobile Accessories", icon: Icons.headset, page: MobileAccessoriesPage()), ItemModel(item: "Computers", icon: Icons.computer, page: ComputersPage()), ItemModel(item: "Televisions", icon: Icons.tv, page: TVPage()),

// These will use the next page ItemModel(item: "Large Appliances", icon: Icons.local_laundry_service, page: LargeAppPage()), ItemModel(item: "Kitchen Appliances", icon: Icons.kitchen, page: KitchenApplsPage()), ItemModel(item: "Home Appliances", icon: Icons.home, page: HomeApplsPage()), ItemModel(item: "Home Entertainment Systems", icon: Icons.devices_other, page: HomeEntSysPage()), ItemModel(item: "Head Phones", icon: Icons.headset_mic,page: HeadphonesPage()), ItemModel(item: "Cameras", icon: Icons.photo_camera,page:CamerasPage()), ItemModel(item: "Speakers", icon: Icons.speaker,page:SpeakersPage()), ItemModel(item: "Camera Accessories", icon: Icons.camera_roll,page:CamAccrsPage()), ];

class MyHomePage extends StatefulWidget { MyHomePage({Key key}) : super(key: key);

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

class _MyHomePageState extends State { String item; ViewModel viewModel; @override void initState() { super.initState(); }

@override Widget build(BuildContext context) { if (viewModel == null) { viewModel = Provider.of(context); viewModel.getAllCategories(); } return new WillPopScope( onWillPop: () async => false, child: new Scaffold( appBar: AppBar( centerTitle: true, backgroundColor: Colors.blue, title: new Text("Gadget Inventory", style: TextStyle(fontSize: 20), textAlign: TextAlign.center), ),

  body: Center(
      child: GridView.count(
        primary: false,
        padding: const EdgeInsets.all(20),
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
        crossAxisCount: 2,
        childAspectRatio: 1,

        children: items.map((item) => Container(
          //  color: Colors.cyan[100],
          child: GestureDetector(
              onTap: () {
                if (item.page != null) {
                  //Navigate to the Page you have
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) => item.page,

                    ),
                  );
                }

              },

              child: Card(
                elevation: 2,
                margin: EdgeInsets.all(5.0),
                //color: Colors.cyan[100],
                shape: new RoundedRectangleBorder(
                    borderRadius: new BorderRadius.circular(20.0)),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Icon(item.icon, size: 90),
                    SizedBox(height: 20),

                    Text(item.item,
                        style:
                        TextStyle(color: Colors.blue, fontSize: 14.0,fontWeight: FontWeight.bold ),
                        textAlign: TextAlign.center),

                  ],
                ),
              )),
  ),

        )

            .toList(),
        //  itemCount: viewModel.categories.length,
        // primary: false,
        //  padding: const EdgeInsets.all(20),
      )),

  /*  floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
  floatingActionButton: FloatingActionButton(
    backgroundColor: Colors.red,
    mini: false,
    highlightElevation: 20.0,
    //shape: BeveledRectangleBorder(borderRadius:BorderRadius.all(Radius.circular(16.0)) ),
    onPressed: () {

      setState(() {
        items.add(ItemModel(
            item: "", icon: Icons.star, page: MyFormPage()

        ));
      });
      debugPrint("Add New Device Category");
      Navigator.push(context, MaterialPageRoute(builder: (context) {
        return AddCategory(
          viewModel: viewModel,

        );
      })); //
    },
    tooltip: 'Add Device Cattegorry',
    child: Icon(Icons.add),
  ),*/

  /* bottomNavigationBar: BottomNavigationBar(
    items: [
  BottomNavigationBarItem(icon: Image.asset('images/cgg.png')),
      //color: Color(0xFF3A5A98),
    ],
  ),*/

  //

 /* floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
  floatingActionButton: FloatingActionButton(
    backgroundColor: Colors.red,

    mini: false,
    highlightElevation: 20.0,
    //shape: BeveledRectangleBorder(borderRadius:BorderRadius.all(Radius.circular(16.0)) ),

onPressed: () {
debugPrint("Add New Device Category");
Navigator.push(context, MaterialPageRoute(builder: (context) {
return AddCategory(
viewModel: viewModel,
);
})); //
},
tooltip: 'Add Device Cattegorry',
child: Icon(Icons.add),

),*/
)
);

}

getIconData(String iconName) { try { return iconData[iconData.keys.firstWhere((key) => key == iconName)]; } catch (e) { return Icons.star; } } }

Map<String, IconData> iconData = { "Mobile": Icons.smartphone, "Mobile Accessories" : Icons.headset, "Computers": Icons.computer, "Televisions": Icons.tv, "Large Appliances" : Icons.local_laundry_service, "Kitchen Appliances" :Icons.kitchen, "Home Appliances" : Icons.home, "Home Entertainment Systems" : Icons.devices_other, "Head Phones" : Icons.headset_mic, "Cameras" : Icons.photo_camera, "Speakers" : Icons.speaker, "Camera Accessories" : Icons.camera_roll,

};

class ItemModel { String item; IconData icon; Widget page; ItemModel({this.item, this.icon, this.page}); }

// Pages [NOTE]: You can use one page fpr all of them and pass the item to that page

class NextPage extends StatefulWidget { NextPage({Key key, this.model}) : super(key: key); final ItemModel model; @override _NextPageState createState() => _NextPageState(); }

class _NextPageState extends State { @override Widget build(BuildContext context) {

return Scaffold(
    appBar: AppBar(
      title: Text(widget.model.item),
    ),
    backgroundColor: Colors.white,
  body: Center(
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
          maxCrossAxisExtent: 200,
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
          childAspectRatio: 1,
        ),
        itemBuilder: (context, item) {
          return Container(
            child: GestureDetector(
                onTap: () {
                  //Navigate to the Page you have
                  var viewModel;
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) => ItemDetailPage(
                        category: viewModel.categories[item],
                      ),
                    ),
                  );
                },
                child: Card(
                  elevation: 2,
                  margin: EdgeInsets.all(5.0),
                  //color: Colors.cyan[100],
                  shape: new RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(20.0)),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [

                      SizedBox(height: 20),

                    ],
                  ),
                )),
          );
        },

        primary: false,
        padding: const EdgeInsets.all(20),
      )),

);

} }

Following are the .dart files for adding cattegorry option

                                         add_cattegorry.dart

// Pages [NOTE]: You can use one page fpr all of them and pass the item to that page

import 'category.dart'; import 'items_model.dart'; import 'package:flutter/material.dart'; import 'package:uuid/uuid.dart';

import 'main.dart';

class AddCategory extends StatefulWidget { ViewModel viewModel; AddCategory({Key key, this.viewModel}) : super(key: key); @override _AddCategoryState createState() => _AddCategoryState(); }

class _AddCategoryState extends State { TextEditingController controller; String dropdownValue;

@override void initState() { controller = TextEditingController(); super.initState(); }

@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Add New Category"), ), backgroundColor: Colors.white, body: Container( padding: EdgeInsets.all(20), child: Center( child: Column( children: [ Padding( padding: const EdgeInsets.symmetric(vertical: 20.0), child: TextField( controller: controller, decoration: InputDecoration( hintText: "Enter category", border: OutlineInputBorder())), ), Padding( padding: const EdgeInsets.symmetric(vertical: 10.0), child: SizedBox( width: double.infinity, child: DropdownButton( value: dropdownValue, icon: Icon( Icons.arrow_downward, size: 16, ), isExpanded: true, iconSize: 12, elevation: 16, style: TextStyle(color: Colors.deepPurple), underline: Container( height: 2, color: Colors.lightBlueAccent, ), onChanged: (String newValue) { setState(() { dropdownValue = newValue; }); }, items: iconData.keys .map<DropdownMenuItem>((String value) { return DropdownMenuItem( value: value, child: Text(value)); }).toList(), ), ), ), SizedBox( width: double.infinity, height: 50, child: RaisedButton( onPressed: () { if (controller.text.isNotEmpty || dropdownValue == null) { setState(() { var category = Category() ..id = Uuid().toString() ..name = controller.text.trim() ..iconName = dropdownValue.toString(); widget.viewModel.addCategory(category); }); Navigator.pop(context); } }, child: Text("Add"), )) ], )))); } }

                                                                         category.dart

import 'package:flutter/cupertino.dart'; import 'package:hive/hive.dart';

part 'category.g.dart';

@HiveType(typeId: 1) class Category extends HiveObject { @HiveField(0) String id;

@HiveField(1) String name;

@HiveField(3) String iconName;

@override String toString() { return '$id: $name'; } }

                                                                       item_details.dart

import 'package:sqlite_crud_flutter/ShowDetails.dart';

import 'category.dart'; import 'items_model.dart'; import 'add_item_pages.dart'; import 'view_items_views.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart';

class ItemDetailPage extends StatefulWidget { final Category category; ItemDetailPage({this.category});

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

class _ItemDetailPageState extends State { ViewModel viewModel;

@override Widget build(BuildContext context) { if (viewModel == null) { viewModel = Provider.of(context); }

return Scaffold(
  appBar: AppBar(
    title: Text(widget.category.name),
    actions: <Widget>[
      IconButton(
          icon: Icon(Icons.add),
          onPressed: () {
            Navigator.push(context, MaterialPageRoute(builder: (context) {
              return ShowDetails();
            }
            )
            ); //
          })
    ],
  ),
  body: Center(
      child: GridView.count(
    primary: false,
    padding: const EdgeInsets.all(20),
    crossAxisSpacing: 10,
    mainAxisSpacing: 10,
    crossAxisCount: 2,
    childAspectRatio: 1,
    children: viewModel.items
        .map(
          (item) => Container(
            //  color: Colors.cyan[100],
            child: GestureDetector(
                onTap: () {
                  //Navigate to the Page you have
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) => ViewItem(
                        item: item,
                      ),
                    ),
                  );
                },
                child: Card(
                  elevation: 2,
                  margin: EdgeInsets.all(5.0),
                  //color: Colors.cyan[100],
                  shape: new RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(20.0)),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Icon(Icons.smartphone),
                      SizedBox(height: 20),
                      Text(item.modelName,
                          style: TextStyle(
                              color: Colors.blue,
                              fontSize: 14.0,
                              fontWeight: FontWeight.bold),
                          textAlign: TextAlign.center),
                    ],
                  ),
                )),
          ),
        )
        .toList(),
  )),
);

} }

I have attached the screenshots of my requirement please help me achieve this functionality .

Please find the screenshots of my requirement here https://groups.google.com/g/flutter-dev/c/YxTbaL_TU78

jamesblasco commented 3 years ago

Sorry this is not an issue related to the library, and I don't understand well what are you asking