Pen Settings

JavaScript

Babel includes JSX processing.

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

Flutter

              
                import 'dart:async';

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: BigPage(),
    ),
  );
}

class BigPage extends StatefulWidget {
  @override
  _BigPageStateWithOpt createState() => _BigPageStateWithOpt();
}

/// 优化前的版本,每次刷新时间都会导致 BigPage rebuild
class _BigPageState extends State<BigPage> {

  Timer _timer;
  int _count = 0;

  @override
  void initState() {
    super.initState();
    _timer = Timer.periodic(const Duration(seconds: 1), (_) {
      setState(() {
        _count++;
      });
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('$_count'),
      ),
      body: Builder(builder: (context) {
        // 假装这里有个很复杂的 build 逻辑
        return Container();
      }),
    );
  }
}

/// 优化后的版本
class _BigPageStateWithOpt extends State<BigPage> {

  Timer _timer;
  int _count = 0;
  StreamController<int> _streamController;

  @override
  void initState() {
    super.initState();
    _streamController = StreamController();
    _timer = Timer.periodic(const Duration(seconds: 1), (_) {
      _streamController.add(++_count);
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    _streamController?.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: StreamBuilder(
          initialData: _count,
          stream: _streamController.stream,
          builder: (context, snapshot) {
            return Text('${snapshot.data}');
          },
        ),
      ),
      body: Builder(builder: (context) {
        // 假装这里有个很复杂的 build 逻辑
        return Container();
      }),
    );
  }
}
              
            
!
999px

Console