name27 / flutter

0 stars 0 forks source link

강아지리스트 패키지 사용: connectivity_plus, pull_to_refresh, Shimmer, FutureBuilder #76

Open name27 opened 1 year ago

name27 commented 1 year ago

2023-02-15 (2)

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shimmer/shimmer.dart';

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

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

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

class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<MainPage> createState() => _MainPageState();
}

RefreshController _refreshController = RefreshController();

class _MainPageState extends State<MainPage> {
  var dio = Dio();
  var url = "https://sfacassignment-default-rtdb.firebaseio.com/.json";
  List<Map<String, dynamic>> dogList = [];
  void getData() async {
    var res = await dio.get(url);
    for (int i = 0; i < res.data["body"].length; i++) {
      dogList.add({});
      dogList[i].addAll({
        "msg": "${res.data["body"][i]["msg"]}",
        "url": "${res.data["body"][i]["url"]}"
      });
    }
    setState(() {});
  }

  void initState() {
    super.initState();
    checkWifi();
    getData();
  }

  void _onRefresh() async {
    imageLoading();
    dogList = [];
    getData();
    await Future.delayed(Duration(milliseconds: 1000));
    _refreshController.refreshCompleted();
  }

  void imageLoading() async {
    isLoading = true;
    await Future.delayed(Duration(milliseconds: 1000))
        .then((value) => setState(() {
              isLoading = false;
            }));
  }

  String wifiText = "";
  bool isWaitWifi = true;
  bool isLoading = true;

  checkWifi() async {
    wifiText = "인터넷 연결 확인 중입니다.";
    await Future.delayed(const Duration(milliseconds: 1200));
    imageLoading();
    final connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      print("모바일 네트워크 연결 확인");
    } else if (connectivityResult == ConnectivityResult.wifi) {
      print("와이파이 연결 확인");
    }
    isWaitWifi = false;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('16일차 과제 2번'),
        actions: [],
      ),
      body: Center(
        child: isWaitWifi
            ? Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(wifiText),
                  CircularProgressIndicator(),
                  SizedBox(
                    width: 200.0,
                    height: 100.0,
                  )
                ],
              )
            : SmartRefresher(
                enablePullUp: false,
                header: WaterDropHeader(
                  waterDropColor: Colors.transparent,
                ),
                controller: _refreshController,
                onRefresh: _onRefresh,
                child: GridView.builder(
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2),
                  itemCount: dogList.length,
                  itemBuilder: (context, index) => isLoading
                      ? Shimmer.fromColors(
                          baseColor: Colors.grey.shade300,
                          highlightColor: Colors.grey.shade100,
                          child: Card(
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(15),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(
                                  height: 120,
                                  decoration: BoxDecoration(
                                      image: DecorationImage(
                                          image: NetworkImage(
                                              dogList[index]["url"]),
                                          fit: BoxFit.contain)),
                                ),
                                SizedBox(height: 3),
                                Center(child: Text(dogList[index]["msg"])),
                                SizedBox(height: 3),
                                IconButton(
                                    onPressed: () {}, icon: Icon(Icons.chat))
                              ],
                            ),
                          ),
                        )
                      : Card(
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(15),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Container(
                                height: 120,
                                decoration: BoxDecoration(
                                    image: DecorationImage(
                                        image:
                                            NetworkImage(dogList[index]["url"]),
                                        fit: BoxFit.contain)),
                              ),
                              SizedBox(height: 3),
                              Center(child: Text(dogList[index]["msg"])),
                              SizedBox(height: 3),
                              IconButton(
                                  onPressed: () {}, icon: Icon(Icons.chat))
                            ],
                          ),
                        ),
                ),
              ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          isWaitWifi = true;
          checkWifi();
          setState(() {});
        },
        child: Icon(Icons.wifi_find),
      ),
    );
  }
}
name27 commented 1 year ago

FutureBuilder로 만들기

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shimmer/shimmer.dart';

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

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

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

class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<MainPage> createState() => _MainPageState();
}

RefreshController _refreshController = RefreshController();

class _MainPageState extends State<MainPage> {
  var dio = Dio();
  var url = "https://sfacassignment-default-rtdb.firebaseio.com/.json";

  List<Map<String, dynamic>> dogList = [];
  String wifiText = "";
  bool isWaitWifi = true;

  void initState() {
    super.initState();
    checkWifi();
    getData();
  }

  getData() async {
    var res = await dio.get(url);
    for (int i = 0; i < res.data["body"].length; i++) {
      dogList.add({});
      dogList[i].addAll({
        "msg": "${res.data["body"][i]["msg"]}",
        "url": "${res.data["body"][i]["url"]}"
      });
    }
    await Future.delayed(Duration(milliseconds: 1500));
  }

  void _onRefresh() async {
    setState(() {});
    await Future.delayed(Duration(milliseconds: 1500));
    _refreshController.refreshCompleted();
  }

  checkWifi() async {
    wifiText = "인터넷 연결 확인 중입니다.";
    await Future.delayed(const Duration(milliseconds: 1500));
    final connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      print("모바일 네트워크 연결 확인");
    } else if (connectivityResult == ConnectivityResult.wifi) {
      print("와이파이 연결 확인");
    }
    isWaitWifi = false;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('16일차 과제 2번'),
      ),
      body: Center(
          child: isWaitWifi
              ? Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(wifiText),
                    CircularProgressIndicator(),
                    SizedBox(
                      width: 200.0,
                      height: 100.0,
                    )
                  ],
                )
              : FutureBuilder(
                  future: getData(),
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.done) {
                      return _dogList();
                    } else {
                      return _loadingDogList();
                    }
                  },
                )),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          isWaitWifi = true;
          checkWifi();
          setState(() {});
        },
        child: Icon(Icons.wifi_find),
      ),
    );
  }

  Widget _dogList() {
    return SmartRefresher(
      enablePullUp: false,
      header: WaterDropHeader(
          waterDropColor: Colors.transparent,
          idleIcon: Icon(
            Icons.refresh_outlined,
            size: 35,
          )),
      controller: _refreshController,
      onRefresh: _onRefresh,
      child: GridView.builder(
        gridDelegate:
            SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
        itemCount: dogList.length,
        itemBuilder: (context, index) => Card(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(15),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                height: 120,
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: NetworkImage(dogList[index]["url"]),
                        fit: BoxFit.contain)),
              ),
              SizedBox(height: 3),
              Center(child: Text(dogList[index]["msg"])),
              SizedBox(height: 3),
              IconButton(onPressed: () {}, icon: Icon(Icons.chat))
            ],
          ),
        ),
      ),
    );
  }

  Widget _loadingDogList() {
    return Shimmer.fromColors(
        baseColor: Colors.grey.shade300,
        highlightColor: Colors.grey.shade100,
        child: GridView.builder(
          gridDelegate:
              SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
          itemCount: dogList.length,
          itemBuilder: (context, index) => Card(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(15),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  height: 120,
                  decoration: BoxDecoration(
                      image: DecorationImage(
                          image: NetworkImage(dogList[index]["url"]),
                          fit: BoxFit.contain)),
                ),
                SizedBox(height: 3),
                Center(child: Text(dogList[index]["msg"])),
                SizedBox(height: 3),
                IconButton(onPressed: () {}, icon: Icon(Icons.chat))
              ],
            ),
          ),
        ));
  }
}
name27 commented 1 year ago

인터넷 연결 확인 후 데이터 요청

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shimmer/shimmer.dart';

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

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

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

class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<MainPage> createState() => _MainPageState();
}

RefreshController _refreshController = RefreshController();

class _MainPageState extends State<MainPage> {
  var dio = Dio();
  var url = "https://sfacassignment-default-rtdb.firebaseio.com/.json";

  List<Map<String, dynamic>> dogList = [];
  String wifiText = "";
  bool isWaitWifi = true;

  void initState() {
    super.initState();
    checkWifi();
  }

  getData() async {
    var res = await dio.get(url);
    for (int i = 0; i < res.data["body"].length; i++) {
      dogList.add({});
      dogList[i].addAll({
        "msg": "${res.data["body"][i]["msg"]}",
        "url": "${res.data["body"][i]["url"]}"
      });
    }
    await Future.delayed(Duration(milliseconds: 1500));
  }

  void _onRefresh() async {
    setState(() {});
    await Future.delayed(Duration(milliseconds: 1500));
    _refreshController.refreshCompleted();
  }

  checkWifi() async {
    wifiText = "인터넷 연결 확인 중입니다.";
    await Future.delayed(const Duration(milliseconds: 1500));
    final connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      print("모바일 네트워크 연결 확인");
      isWaitWifi = false;
    } else if (connectivityResult == ConnectivityResult.wifi) {
      print("와이파이 연결 확인");
      isWaitWifi = false;
    } else {
      wifiText = "인터넷 연결이 되지 않습니다";
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('16일차 과제 2번'),
      ),
      body: Center(
          child: FutureBuilder(
        future: checkWifi(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done && !isWaitWifi) {
            return FutureBuilder(
              future: getData(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  return _dogList();
                } else {
                  return _loadingDogList();
                }
              },
            );
          } else if (!isWaitWifi) {
            return _loadingDogList();
          } else {
            return _checkWifi();
          }
        },
      )),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          isWaitWifi = true;
          checkWifi();
          setState(() {});
        },
        child: Icon(Icons.wifi_find),
      ),
    );
  }

  Widget _checkWifi() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(wifiText),
        CircularProgressIndicator(),
        SizedBox(
          width: 200.0,
          height: 100.0,
        )
      ],
    );
  }

  Widget _dogList() {
    return SmartRefresher(
      enablePullUp: false,
      header: WaterDropHeader(
          waterDropColor: Colors.transparent,
          idleIcon: Icon(
            Icons.refresh_outlined,
            size: 35,
          )),
      controller: _refreshController,
      onRefresh: _onRefresh,
      child: GridView.builder(
        gridDelegate:
            SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
        itemCount: dogList.length,
        itemBuilder: (context, index) => Card(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(15),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                height: 120,
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: NetworkImage(dogList[index]["url"]),
                        fit: BoxFit.contain)),
              ),
              SizedBox(height: 3),
              Center(child: Text(dogList[index]["msg"])),
              SizedBox(height: 3),
              IconButton(onPressed: () {}, icon: Icon(Icons.chat))
            ],
          ),
        ),
      ),
    );
  }

  Widget _loadingDogList() {
    return Shimmer.fromColors(
        baseColor: Colors.grey.shade300,
        highlightColor: Colors.grey.shade100,
        child: GridView.builder(
          gridDelegate:
              SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
          itemCount: 8,
          itemBuilder: (context, index) => Card(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(15),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  height: 120,
                ),
                SizedBox(height: 3),
                Center(child: Text('')),
                SizedBox(height: 3),
                IconButton(onPressed: () {}, icon: Icon(Icons.chat))
              ],
            ),
          ),
        ));
  }
}