1000sj
SJ CODE
1000sj
전체 방문자
오늘
어제
  • 분류 전체보기
    • Security
      • 네트워크
      • 보안
      • CTF
      • Exploit
      • Fuzzing
    • System Programming
      • Kernel
      • Operating System
      • Compiler
      • Device Driver
      • Emulator
      • Parrelel Processing
      • Assembly
    • Application Programming
      • Script
      • Android
    • Cloud Computing
      • Cloud Native
      • Public Cloud
      • Infrastructure
      • Database
      • DevOps
    • TroubleShooting
    • ETC
      • 문화 생활
      • 커뮤니티

인기 글

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
1000sj

SJ CODE

[Flutter] 포켓몬도감
Application Programming

[Flutter] 포켓몬도감

2021. 9. 6. 00:07

Demo

Using

  • state management (provider)
  • api
  • hero animation

 

Data

Provider객체를 main에서 생성해주면 Data를 인스턴스화해서 View와 공유할 수 있다.

 

// http 통신하고 Data 객체를 저장하고 가공한다.
class MyProvider with ChangeNotifier {
  MyState _state = MyState.LOADING;
  Map<String, dynamic> _pokedex = {};

  MyState getState() => _state;
  Map<String, dynamic> getPokeDex() => _pokedex;

  fetchPokeDex() async {
    Uri _uri = Uri.parse(
        "http://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json");

    http.Response _response = await http.get(_uri);

    _pokedex = jsonDecode(_response.body);

    _state = MyState.DONE;
    notifyListeners();
  }
}

 

// Provider를 선언하면 싱글톤으로 생성되어 하위 위젯에서 data에 접근할 수 있음
void main() {
  runApp(MultiProvider(
    providers: [
      ChangeNotifierProvider<MyProvider>(create: (context) => MyProvider()),
    ],
    child: MyApp(),
  ));
}

 

사용할때는 2가지 방법이 있는데 위젯을 감싸는냐, 위젯안에서 불러오느냐가 다르다.

 

Provider.of() 는 위젯안에서 불러오기 때문에 구독(listener)을 할 수 없는 경우가 있다.

Provider.of<MyProvider>(context, listen: false)

 

 

Consumer 객체로 감싸면 그 위젯은 data를 관찰할 수 있고 외부에서 위젯을 변동할 필요가 없어진다.

Consumer<WeatherProvider>(
                builder: (context, value, child) {
                  Weather _weather = value.getWeather();
                  return Column(
                      children: [
                        Text("나라 : " + _weather.sys!.country.toString(), style: s_textStyle),
                      ],
                    );
                }),
      ],),

 

Provider를 생성해놓으면 그 뒤론 데이터 바인딩을 생각할 필요가 없어 편해지지만 처음 빌드할 때 초기값을 받아오는 부분에서 에러가 날 수 있다. 아직 Flutter의 라이프사이클을 잘 모르겠다.

 

HTTP 통신

1. 

// http 의존성 추가
dependencies:
  http: <latest_version>

2. 

// 네트워크 요청
Future<http.Response> fetchPhotos(http.Client client) async {
  return http.Response _response = http.get(uri, header);
}

3. 

// Json Parsing
Map<String, dynamic> jsonMap = jsonDecode(_response.body);

return parsed.map<Model>((jsonMap) => Model.fromJson(json)).toList();

4. 

// isolate : isolate는 compute() 함수를 사용하여 오래걸리는 작업을 백그라운드로 돌린다.
Future<List<PokeDex>> fetchPokeDex() async {
  
  Uri _uri = Uri.parse(
        "http://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json");

  final  http.Response _response = await http.get(_uri);
  
  return compute(PokeDex, response.body);
}

 

Hero Animation

Flutter는 다양한 Animation을 제공한다. Hero Animation은 페이지 리스트 뷰에서 디테일 뷰로 이동할 때 사용하면 좋은 Animation이다.

// list view
GestureDetector(
  onTap: () {
    Navigator.push(
    context,
    MaterialPageRoute(
    builder: (context) => DetailPage(poketmon)));
  },
  child: Hero(
    tag: "tag",
    child: Widget()
  ))

 

// detail view : tag를 list view에서 썼던 것과 똑같이 넣어주면 됨
Hero(
  tag: "tag",
  child: Widget()
)

 

전체 코드

  • https://github.com/sjcoding/poke-dex

Ref

  • Provider 사용법
  • Json 파싱하기
  • Future Builder
  • Hero Animation
  • Animation Sample

 

'Application Programming' 카테고리의 다른 글

[Typescript]  (0) 2021.10.15
[Node.js] Modules  (0) 2021.09.20
[Node.js] Node.js 설치  (0) 2021.09.19
[Flutter] HTTP 통신  (0) 2021.09.07
[Flutter] StatelessWidget  (0) 2021.05.27
    'Application Programming' 카테고리의 다른 글
    • [Node.js] Modules
    • [Node.js] Node.js 설치
    • [Flutter] HTTP 통신
    • [Flutter] StatelessWidget
    1000sj
    1000sj

    티스토리툴바