name27 / flutter

0 stars 0 forks source link

키오스크 앱 shared_preferences #83

Open name27 opened 1 year ago

name27 commented 1 year ago

image

main.dart

import 'package:easy_kiosk_app/main_page.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: MainPage());
  }
}

main_page.dart

import 'package:dio/dio.dart';
import 'package:easy_kiosk_app/OpionCard.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MainPage extends StatefulWidget {
  const MainPage({super.key});
  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  List<String> orderList = [];
  SharedPreferences? prefs;

  var dio = Dio();
  var url = 'http://52.79.115.43:8090/api/collections/options/records';
  var res;

  List<Map<String, dynamic>> option = [];
  @override
  void initState() {
    super.initState();
    getData();
    initPreference();
  }

  getData() async {
    res = await dio.get(url);
    print("한번 출력해봐요 ${res.data["totalItems"]}");
    for (int i = 0; i < res.data["totalItems"]; i++) {
      option.add({});
      option[i].addAll({
        "menu": "${res.data["items"][i]["menu"]}",
        "imgUrl": "${res.data["items"][i]["imageUrl"]}"
      });
    }
  }

  void initPreference() async {
    prefs = await SharedPreferences.getInstance();
    if (prefs != null) {
      print(prefs);
      orderList = prefs!.getStringList('orderList') ?? [];
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('분식왕 이테디 주문하기'),
          centerTitle: true,
          foregroundColor: Colors.black,
          backgroundColor: Colors.transparent,
          elevation: 0,
          actions: [],
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '주문 리스트',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
              orderList.isEmpty
                  ? Center(child: Text('주문할 메뉴가 없습니다'))
                  : Wrap(
                      children: orderList
                          .map((e) => Chip(
                                label: Text(e),
                                onDeleted: () {
                                  orderList.remove(e);
                                  setState(() {});
                                  if (prefs != null) {
                                    prefs!
                                        .setStringList('orderList', orderList);
                                  }
                                },
                              ))
                          .toList(),
                    ),

              SizedBox(
                height: 12,
              ),
              Text(
                '음식',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
              FutureBuilder(
                  future: Future.delayed(Duration(milliseconds: 100)),
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.done) {
                      return Expanded(
                        child: GridView.builder(
                          gridDelegate:
                              SliverGridDelegateWithFixedCrossAxisCount(
                                  crossAxisCount: 3),
                          itemCount: option.length,
                          itemBuilder: (context, index) => InkWell(
                            onTap: (() {
                              setState(
                                  () => orderList.add(option[index]["menu"]));
                              if (prefs != null) {
                                prefs!.setStringList('orderList', orderList);
                              }
                            }),
                            child: OptionCard(
                                imgUrl: option[index]["imgUrl"],
                                foodName: option[index]["menu"]),
                          ),
                        ),
                      );
                    } else
                      return SizedBox();
                  }),
              //_buiddList()
            ],
          ),
        ),
        floatingActionButton: orderList.isNotEmpty
            ? FloatingActionButton.extended(
                onPressed: () {},
                label: Text('결제하기'),
              )
            : null,
        floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat);
  }
}

OptionCard.dart

import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';

class OptionCard extends StatelessWidget {
  const OptionCard({super.key, required this.imgUrl, required this.foodName});
  final String imgUrl;
  final String foodName;
  @override
  Widget build(BuildContext context) {
    return Card(
      child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
        Expanded(
            child: Image.network(
          imgUrl,
          fit: BoxFit.cover,
        )),
        Text(foodName),
        Text('[담기]')
      ]),
    );
  }
}
name27 commented 1 year ago

main_page.dart

import 'package:dio/dio.dart';
import 'package:easy_kiosk_app/OpionCard.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MainPage extends StatefulWidget {
  const MainPage({super.key});
  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  List<String> orderList = [];
  SharedPreferences? prefs;

  var dio = Dio();
  var url = 'http://52.79.115.43:8090/api/collections/options/records';

  List<Map<String, dynamic>> option = [];
  @override
  void initState() {
    super.initState();
    initPreference();
  }

  Future<List<dynamic>> getData() async {
    var res = await dio.get(url);
    if (res.statusCode == 200) {
      return res.data["items"];
    }
    return [];
  }

  void initPreference() async {
    prefs = await SharedPreferences.getInstance();
    if (prefs != null) {
      orderList = prefs!.getStringList('orderList') ?? [];
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('분식왕 이테디 주문하기'),
          centerTitle: true,
          foregroundColor: Colors.black,
          backgroundColor: Colors.transparent,
          elevation: 0,
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '주문 리스트',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
              orderList.isEmpty
                  ? Center(child: Text('주문할 메뉴가 없습니다'))
                  : Wrap(
                      children: orderList
                          .map((e) => Chip(
                                label: Text(e),
                                onDeleted: () {
                                  orderList.remove(e);
                                  setState(() {});
                                  if (prefs != null) {
                                    prefs!
                                        .setStringList('orderList', orderList);
                                  }
                                },
                              ))
                          .toList(),
                    ),

              SizedBox(
                height: 12,
              ),
              Text(
                '음식',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
              Expanded(
                child: FutureBuilder(
                    future: getData(),
                    builder: (context, snapshot) {
                      if (snapshot.connectionState == ConnectionState.done) {
                        return GridView.builder(
                          gridDelegate:
                              SliverGridDelegateWithFixedCrossAxisCount(
                                  crossAxisCount: 3,
                                  mainAxisSpacing: 4,
                                  crossAxisSpacing: 4),
                          itemCount: snapshot.data?.length ?? 0,
                          itemBuilder: (context, index) => OptionCard(
                              onTap: () {
                                orderList.add(snapshot.data![index]["menu"]);
                                if (prefs != null) {
                                  prefs!.setStringList('orderList', orderList);
                                }
                                setState(() {});
                              },
                              imgUrl: snapshot.data![index]["imageUrl"],
                              foodName: snapshot.data![index]["menu"]),
                        );
                      }
                      return Center(child: LinearProgressIndicator());
                    }),
              ),
              //_buiddList()
            ],
          ),
        ),
        floatingActionButton: orderList.isNotEmpty
            ? FloatingActionButton.extended(
                onPressed: () {},
                label: Text('결제하기'),
              )
            : null,
        floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat);
  }
}

OptionCard.dart

import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';

class OptionCard extends StatelessWidget {
  const OptionCard(
      {super.key,
      required this.imgUrl,
      required this.foodName,
      required this.onTap});
  final String imgUrl;
  final String foodName;
  final Function() onTap;
  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: Card(
        child:
            Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
          Expanded(
              child: Image.network(
            imgUrl,
            fit: BoxFit.cover,
          )),
          Text(foodName),
          Text('[담기]')
        ]),
      ),
    );
  }
}