flutter_clean_architecture_v2(InheritedWidget)

jju·2024년 1월 21일
0
home: HomeScreen(api : PixabayApi()),

v_1에 main.dart에서 생성자로 데이터를 받고 전달하는 방식이였는데 해당 문제점은 온갖것들이 main.dart에서 지정하게 되므로 이를 해결하고자 합니다.

InheritedWidget은 어떤 위젯트리에도 원한 객체를 전달해 줄 수 있는 위젯입니다. 필요한 데이터를 하위 위젯에 전달해주기 위함

InheritedWidget 의 기본구조입니다.

import 'package:flutter/cupertino.dart';

InheritedWidget은 어떤 위젯트리에도 원한 객체를 전달해 줄 수 있는 위젯입니다.
class PhotoProvider extends InheritedWidget {
  const PhotoProvider({Key? key, required Widget child})
      : super(key: key, child: child);

  @override
  bool updateShouldNotify(covariant InheritedWidget oldWidget) {
    // TODO: implement updateShouldNotify
    throw UnimplementedError();
  }
}

InheritedWidget 전달예시)

  • 생성자를 바로 전달하는게 아닌, InheritedWidget를 통해서 하위 위젯으로 전달하기 때문에 of(BuildContext context)를 이용
// InheritedWidget은 어떤 위젯트리에도 원한 객체를 전달해 줄 수 있는 위젯입니다.
class PhotoProvider extends InheritedWidget {
  final PixabayApi api;

  const PhotoProvider({Key? key, required this.api, required Widget child})
      : super(key: key, child: child);

  static PhotoProvider of(BuildContext context){ //위젯트리의 정보를 가지고 있는 객체
    final PhotoProvider? result = context.dependOnInheritedWidgetOfExactType<PhotoProvider>(); // 가장 가까운 PhotoProvider를 찾아서 return
    assert(result != null,'No PixabayApi found in context'); //null 이면 문구가 나옵니다. 널이 아니다라는 검증
    return result!;
  }

  @override //이전 상태와 현재 상태가 다른지 확인하는 위젯
  bool updateShouldNotify(PhotoProvider oldWidget) {
    return oldWidget.api != api;
  }
}

하위 위젯이 데이터 전달예시)

@override
  Widget build(BuildContext context) {
    final photoProvider = PhotoProvider.of(context); //of의 함수를 지정해줘서 context를 제공합니다. InheritedWidget의 of
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text(
          '이미지 검색 앱',
          style: TextStyle(color: Colors.black),
        ),
        backgroundColor: Colors.white,
        elevation: 0,
      ),
      body: Column(
        children: [
          Padding(
            padding: EdgeInsets.all(16.0),
            child: TextField(
              controller: _controller,
              decoration: InputDecoration(
                border: const OutlineInputBorder(
                  borderRadius: BorderRadius.all(
                    Radius.circular(10.0),
                  ),
                ),
                suffixIcon: IconButton(
                  onPressed: () async {
                    final photos = await photoProvider.api.fetch(_controller.text);  //photos 는 작명이지만 역할이 있습니다. fetch 를 받는 pohto 모델의 photos 입니다.
                    setState(() { 
                      _photos = photos; //controller.text 사용자 입력에 따라 pthos 가 _photos에 들어가면서 화면이 다시 그려지게 됩니다.
                    });

                  },

main.dart

 home: PhotoProvider(
        api: PixabayApi(),
        child: const HomeScreen(),
      ),
profile
한결

0개의 댓글