GitHub 저장소wolfenrain/stateless

상태 없는

상태가 없는 상태 관리 패키지이지만, 실제로는 상태가 있습니다.

상태 없는 프로젝트 이미지
스타
39
포크
2
최근 푸시(UTC)
2023. 2. 8.
프로젝트 상태
활성

원본 README

아래는 영문 원문 스냅샷입니다. 최신 내용은 GitHub에서 확인하세요.

Stateless

A stateless stateful state management package that is not stateless.

stateless coverage style: very good analysis License: MIT pub package


DISCLAIMER: Please do not use this package in production, it uses Dart Magic under the hood that could break whenever Flutter wants it to break.

Introduction

The goal of this package is to see if we can have state management without having to care about state management. The learning curve of Stateless should be at a minimal, knowledge developers have from known Flutter APIs should be transferable, like initState, dispose and build.

Getting Started

In your flutter project, add the following in your pubspec.yaml:

  dependencies:
    stateless: ^0.1.0

Usage

The classic Flutter Counter Widget, rewritten with Stateless:

import 'package:flutter/material.dart';
import 'package:stateless/stateless.dart';

void main() => runApp(const MyApp());

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Stateless Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.blue),
      home: MyHomePage(title: 'Stateless Demo Home Page'),
    );
  }
}

// We define the interface that will describe our state data.
abstract class MyCounterState {
  late int counter;
}

// We extends from Stateless to create our stateless stateful widget.
class MyHomePage extends Stateless implements MyCounterState {
  MyHomePage({super.key, required this.title});

  final String title;

  @override
  void initState() {
    super.initState();
    // Initialize our state data.
    counter = 0;
  }

  void showSnackBar() {
    // We can access the BuildContext from anywhere in our widget.
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('The count is at: $counter')),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(title)),
      body: const Center(child: MyCounterText()),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FloatingActionButton(
            // Update the counter by just simply incrementing it.
            onPressed: () => counter++,
            tooltip: 'Increment',
            child: const Icon(Icons.add),
          ),
          const SizedBox(height: 8),
          FloatingActionButton(
            onPressed: showSnackBar,
            tooltip: 'Show SnackBar',
            child: const Icon(Icons.lightbulb),
          ),
        ],
      ),
    );
  }
}

As you can see the API is barely any different from normal Flutter widgets, by extending from Stateless and implementing our state interface we can just update the interface properties and it will automatically know that it's state has changed and therefore triggers a rebuild.

Accessing state data in a child

Quite often you want to access state data from a parent in the tree, well Stateless is capable of doing that for you!

Lets re-imagine the above counter app into two parts, one is the Stateless widget and the second part is a normal StatelessWidget that displays the counter value.

class MyHomePage extends Stateless implements MyCounter {
  ... 

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(title)),
      // We build our custom text counter widget here.
      body: const Center(child: MyCounterText()),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FloatingActionButton(
            onPressed: () => counter++,
            tooltip: 'Increment',
            child: const Icon(Icons.add),
          ),
          const SizedBox(height: 8),
          FloatingActionButton(
            onPressed: showSnackBar,
            tooltip: 'Show SnackBar',
            child: const Icon(Icons.lightbulb),
          ),
        ],
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    // We can then observe our MyCounter for state changes.
    final myCounter = context.observe<MyCounter>();

    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const Text('You have pushed the button this many times:'),
        Text(
          '${myCounter.counter}',
          style: Theme.of(context).textTheme.headline4,
        ),
      ],
    );
  }
}

Our MyCounterText widget can simply observe the state of our MyCounter and read the current counter value from it.

Contributing

Interested in contributing? We love pull request! See the Contribution document for more information.

Jochum van der Ploeg GitHub avatar
GitHub 작성자

Jochum van der Ploeg ↗

Open saucing for @bluefireteam 💙 • proud husbird • he/him • 🏳️‍🌈

언어Dart

분류

이 저장소가 배포한 패키지

사용 중인 의존성

의존성 목록 4 개

  • flutter{"sdk":"flutter"}
  • flutter_test개발 의존성{"sdk":"flutter"}
  • mocktail개발 의존성^0.3.0
  • very_good_analysis개발 의존성^3.0.1

프로젝트에 맞는 저장소를 선택하려면?

사용 목적에 따라 검색하고 개발 활동을 비교한 뒤 원본 저장소에서 요구 사항을 확인하세요.

  1. 이름, 작성자 또는 설명으로 검색하고 기술 주제로 범위를 좁힙니다.
  2. 스타, 포크, 최근 푸시를 함께 비교하세요. 스타는 관심의 지표이며 품질을 보장하지 않습니다.
  3. 사용하기 전에 GitHub에서 README, 라이선스, Issues를 확인하세요.

출처 및 관리

“A repository is the most basic element of GitHub.”

GitHub Docs — About repositories ↗