Commit Graph

487 Commits

Author SHA1 Message Date
Huy
fa5254331f
Add ability to disable CupertinoSegmentedControl (#152813)
### Summary

Add the ability to configure enabled or disabled segments in CupertinoSegmentedControl. The idea is to pass a `segmentStates` map, where the user can set the state according to segment key. User can also set background and text colors when the segment is disabled.

### Demo

https://github.com/user-attachments/assets/4a02da02-a0fb-4ded-a271-033a8dc79ac3

### Related issue
Fixes https://github.com/flutter/flutter/issues/52105
2024-10-24 12:05:35 +00:00
Nate Wilson
ea0fda51ef
WidgetStateInputBorder (#157190)
**Changes**
- Add `WidgetStateInputBorder` class, with `.resolveWith()` and `.fromMap()` constructors
- Deprecate `MaterialStateOutlineInputBorder` and `MaterialStateUnderlineInputBorder` and provide data-driven fixes

<br>

**Other changes** based on https://github.com/flutter/flutter/pull/154972#pullrequestreview-2344092821
- Fix documentation copy-paste typo ("OutlinedBorder" → "InputBorder")
- Add test to ensure borders are painted correctly
- Add DartPad sample & relevant test
2024-10-22 23:45:41 +00:00
Jiten Patel
3e9901dac9
Fix: showDatePicker should have a simple example in the docs (#156196)
This PR introduces a basic example of how to use the `showDatePicker` function. The purpose of this PR is to simplify the onboarding process for new Flutter developers by providing a straightforward demonstration of handling the asynchronous Future returned by the showDatePicker. This will help users unfamiliar with the intricacies of asynchronous operations in Flutter.

Fixes #156157
2024-10-22 17:04:23 +00:00
Valentin Vignal
a484aa260b
Add test for selectable_region.0.dart (#157258)
Contributes to https://github.com/flutter/flutter/issues/130459

It adds a test for
- `examples/api/test/material/selectable_region/selectable_region.0_test.dart`
2024-10-22 07:25:25 +00:00
Valentin Vignal
3405f11e5c
Add test for flexible_space_bar.0.dart (#157107)
Contributes to https://github.com/flutter/flutter/issues/130459

It adds a test for
- `examples/api/test/material/flexible_space_bar/flexible_space_bar.0_test.dart`
2024-10-21 15:17:14 +00:00
Nate Wilson
6b1bc456f4
Arrow syntax for getters (#156483)
This egotistical PR aims to draw attention to a [style guideline](https://github.com/flutter/flutter/blob/master/docs/contributing/Style-guide-for-Flutter-repo.md#use--for-getters-and-callbacks-that-just-return-literals-or-switch-expressions) that I changed:

> #### Use `=>` for getters and callbacks that just return literals or switch expressions

<br>

There was an opportunity for valuable discussion in #154753 about how this structure affects readability, but I shut it down pretty quick since there was a lot of other stuff going on there.

Interested to hear thoughts from @Piinks and others.
2024-10-17 19:25:14 +00:00
Victor Sanni
f9eebe0319
Add bottom to CupertinoNavigationBar to allow for a double-row nav bar (#155959)
Fixes [Support segmented controls in nav bars and double row nav bars](https://github.com/flutter/flutter/issues/10469)

<img width="270" height="600"  alt="Screenshot 2024-09-30 at 3 09 04 PM" src="https://github.com/user-attachments/assets/4003116f-69dd-4f8f-a185-6ca151b74d2d">
2024-10-16 19:36:55 +00:00
Victor Sanni
293ae2e5ab
Add bottom to CupertinoSliverNavigationBar (#155841)
Fixes [Support search box inside large title nav bar](https://github.com/flutter/flutter/issues/18103)
Part of [Support segmented controls in nav bars and double row nav bars](https://github.com/flutter/flutter/issues/10469)

## None mode (Current default)

https://github.com/user-attachments/assets/d798314e-940f-4311-9a9a-fe999c65f280

## Always mode

https://github.com/user-attachments/assets/950a85aa-8ca2-42ea-bf8b-3cb8f95e616e

## Automatic mode

https://github.com/user-attachments/assets/c7c7240b-d493-4036-a987-30f61d02bac3

## With CupertinoSlidingSegmentedControl

https://github.com/user-attachments/assets/59f4aec4-8d9c-4223-915b-97b73cb25dc8

<details>
<summary>Sample Code</summary>

```dart
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/cupertino.dart';

/// Flutter code sample for [CupertinoSliverNavigationBar].

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

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

  @override
  Widget build(BuildContext context) {
    return const CupertinoApp(
      theme: CupertinoThemeData(brightness: Brightness.light),
      home: SliverNavBarExample(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return const CupertinoPageScaffold(
      // A ScrollView that creates custom scroll effects using slivers.
      child: SafeArea(
        child: CustomScrollView(
          // A list of sliver widgets.
          slivers: <Widget>[
            CupertinoSliverNavigationBar(
              leading: SizedBox(
                width: 100,
                child: Row(
                  children: [
                    Icon(CupertinoIcons.back),
                    Text(
                      'Lists',
                      style: TextStyle(color: CupertinoColors.activeBlue),
                    ),
                  ],
                ),
              ),
              trailing: Icon(CupertinoIcons.plus),
              largeTitle: Text('iPhone'),
              // Change to desired mode.
              drawerMode: NavigationDrawerMode.none,
              drawer: Padding(
                padding: EdgeInsets.fromLTRB(8.0, 0.0, 8.0, 16.0),
                child: CupertinoSearchTextField(),
              ),
            ),
            SliverFillRemaining(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Text('Drag me up', textAlign: TextAlign.center),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
```

</details>
2024-10-16 18:25:06 +00:00
Bruno Leroux
e08ad36dd9
Remove LogicalKeySet usage in one Shortcuts example (#156941)
## Description

This PR replaces `LogicalKeySet` by `SingleActivator` in one of the Shortcuts example.
According to [LogicalKeySet documentation](https://api.flutter.dev/flutter/widgets/LogicalKeySet-class.html) :
"prefer [SingleActivator](https://api.flutter.dev/flutter/widgets/SingleActivator-class.html) when possible, whose behavior more closely resembles that of typical platforms".

## Related Issue

Related to [LogicalKeySet Not Working on Linux Environment](https://github.com/flutter/flutter/issues/156806).

## Tests

Adds 1 test.
2024-10-16 17:15:06 +00:00
RamonFarizel
51aa2f5809
Add code sample to the CupertinoMagnifier/CupertinoTextMagnifier (#156028)
This PR adds code samples regarding the CupertinoMagnifier and CupertinoTextMagnifier

Fixes #154439
2024-10-11 20:53:18 +00:00
Bruno Leroux
480869afe7
Update MenuAnchor API examples (#156404)
## Description

Cleanup MenuAnchor API examples:
- Remove usage of useMaterial3
- fix some formatting issues
2024-10-08 19:15:07 +00:00
Nate Wilson
5ecf10052f
pattern-matching refactor (#154753)
This pull request aims to improve code readability, based on feedback gathered in a recent design doc.

<br>

There are two factors that hugely impact how easy it is to understand a piece of code: **verbosity** and **complexity**.

Reducing **verbosity** is important, because boilerplate makes a project more difficult to navigate. It also has a tendency to make one's eyes gloss over, and subtle typos/bugs become more likely to slip through.

Reducing **complexity** makes the code more accessible to more people. This is especially important for open-source projects like Flutter, where the code is read by those who make contributions, as well as others who read through source code as they debug their own projects.

<hr>

<br>

The following examples show how pattern-matching might affect these two factors:

<details> <summary><h3>Example 1 (GOOD)</h3> [click to expand]</summary>

```dart
if (ancestor case InheritedElement(:final InheritedTheme widget)) {
  themes.add(widget);
}
```

Without using patterns, this might expand to

```dart
if (ancestor is InheritedElement) {
  final InheritedWidget widget = ancestor.widget;
  if (widget is InheritedTheme) {
    themes.add(widget);
  }
}
```

Had `ancestor` been a non-local variable, it would need to be "converted" as well:

```dart
final Element ancestor = this.ancestor;
if (ancestor is InheritedElement) {
  final InheritedWidget inheritedWidget = ancestor.widget;
  if (widget is InheritedTheme) {
    themes.add(theme);
  }
}
```

</details>

<details> <summary><h3>Example 2 (BAD) </h3> [click to expand]</summary>

```dart
if (widget case PreferredSizeWidget(preferredSize: Size(:final double height))) {
  return height;
}
```

Assuming `widget` is a non-local variable, this would expand to:

```dart
final Widget widget = this.widget;
if (widget is PreferredSizeWidget) {
  return widget.preferredSize.height;
}
```

<br>

</details>

In both of the examples above, an `if-case` statement simultaneously verifies that an object meets the specified criteria and performs a variable assignment accordingly.

But there are some differences: Example 2 uses a more deeply-nested pattern than Example 1 but makes fewer useful checks.

**Example 1:**
- checks that `ancestor` is an `InheritedElement`
- checks that the inherited element's `widget` is an `InheritedTheme`

**Example 2:**
- checks that `widget` is a `PreferredSizeWidget`
(every `PreferredSizeWidget` has a `size` field, and every `Size` has a `height` field)

<br>

<hr>

I feel hesitant to try presenting a set of cut-and-dry rules as to which scenarios should/shouldn't use pattern-matching, since there are an abundance of different types of patterns, and an abundance of different places where they might be used.

But hopefully the conversations we've had recently will help us converge toward a common intuition of how pattern-matching can best be utilized for improved readability.

<br><br>

- resolves https://github.com/flutter/flutter/issues/152313
- Design Doc: [flutter.dev/go/dart-patterns](https://flutter.dev/go/dart-patterns)
2024-10-03 18:21:04 +00:00
Mitchell Goodwin
d877d2875e
Allow mixing route transitions in one app. (#150031)
Fixes #33799

Allows for a route to inform the route below it in the navigation stack how to animate when the topmost route enters are leaves the stack.

It does this by making a `DelegatedTransition` available for the previous route to look up and use. If available, the route lower in the stack will wrap it's transition builders with that delegated transition and use it instead of it's default secondary transition.

This is what the sample code in this PR shows an app that is able to use both a Material zoom transition and a Cupertino slide transition in one app. It also includes a custom vertical transition. Every page animates off the screen in a way to match up with the incoming page's transition. When popped, the correct transitions play in reverse.

https://github.com/user-attachments/assets/1fc910fa-8cde-4e05-898e-daad8ff4a697

The below video shows this logic making a pseudo iOS styled sheet transition.

https://github.com/flutter/flutter/assets/58190796/207163d8-d87f-48b1-aad9-7e770d1d96c5

All existing page transitions in Flutter will be overwritten by the incoming route if a `delegatedTransition` is provided. This can be opted out of through `canTransitionTo` for a new route widget. Of Flutter's existing page transitions, this PR only adds a `DelegatedTransition` for the Zoom and Cupertino transitions. The other transitions possible in Material will get delegated transitions in a later PR.
2024-10-02 20:08:11 +00:00
Sikandar Sadaqat
d355a474f9
[Docs] CupertinoListTile API Example (#154548)
This PR adds an example for CupertinoListTile

Fixes: https://github.com/flutter/flutter/issues/154438
2024-10-02 15:24:05 +00:00
Bruno Leroux
21381d843f
Fix DropdownMenu does not rematch initialSelection when entries have changed (#155757)
## Description

This PR makes DropdownMenu rematching the initialSelection when the entries are updated.
If the new entries contains one entry whose value matches `initialSelection` this entry's label is used to initialize the inner text field, if no entries matches `initialSelection` the text field is emptied.

## Related Issue

Fixes [DropdownMenu.didUpdateWidget should re-match initialSelection when dropdownMenuEntries have changed](https://github.com/flutter/flutter/issues/155660).

## Tests

Adds 3 tests.
2024-10-02 12:03:20 +00:00
Kostia Sokolovskyi
591cc39c2d
Add WidgetStateMouseCursor example and tests for it. (#155552)
Fixes https://github.com/flutter/flutter/issues/155551

### Description
- Adds example for `WidgetStateMouseCursor`
- Adds tests for `examples/api/lib/widgets/widget_state/widget_state_mouse_cursor.0.dart`
2024-10-01 23:15:53 +00:00
Denis Gordin
31d6b35b7f
Move FlutterLogo from material to widget (#155864)
The PR is moving FlutterLogo from `lib/src/material` to `lib/src/widgets` because it has no dependency on Material.

Issue: https://github.com/flutter/flutter/issues/154448

PS: There is [older PR](https://github.com/flutter/flutter/pull/154711) for this issue and I don't know the policy on conflicting PRs. Let me know if I need to drop mine.
2024-09-30 17:19:25 +00:00
Taha Tesser
9f88de930b
Optimize Overlay sample to avoid overflow (#155861)
Fixes [Optimize official `Overlay` sample to avoid overflowing.](https://github.com/flutter/flutter/issues/155860)

When checking https://main-api.flutter.dev/flutter/widgets/Overlay-class.html on a laptop screen it overflows as the layout uses Row instead of more robust widget for spacing `Wrap`

Quick Friday night fix. :) 

| Before | After |
| --------------- | --------------- |
| <img src="https://github.com/user-attachments/assets/eea6f1d9-e860-4ebd-8d16-2d8f4141e1ec" /> | <img src="https://github.com/user-attachments/assets/9f8426ba-d541-44a6-8ea6-2e34636b7e82"  /> |
2024-09-28 09:20:32 +00:00
Kostia Sokolovskyi
ce24dd6a76
Add WidgetStateBorderSide example and tests for it. (#155559)
Fixes https://github.com/flutter/flutter/issues/155557

### Description
- Adds example for `WidgetStateBorderSide`
- Adds tests for `examples/api/lib/widgets/widget_state/widget_state_border_side.0.dart`
2024-09-25 15:53:28 +00:00
Kostia Sokolovskyi
96ba3c555a
Add WidgetStateProperty example and tests for it. (#155315)
This PR contributes to https://github.com/flutter/flutter/issues/155313

### Description
- Adds example for `WidgetStateProperty`
- Adds tests for `examples/api/lib/widgets/widget_state/widget_state_property.0.dart`
2024-09-24 00:31:07 +00:00
Nate Wilson
bfa04edca6
un-break ThemeData equality (#154695)
This PR is _almost_ able to close issue #89127.

Sadly, no `InheritedModel` or custom `RenderObject`s today; instead the [WidgetState operators](https://main-api.flutter.dev/flutter/widgets/WidgetStateOperators.html) have been restructured to support equality checks.

`WidgetStateProperty.fromMap()` is now capable of accurate equality checks, and all of the `.styleFrom()` methods have been refactored to use that constructor.

(Equality checks are still broken for `WidgetStateProperty.resolveWith()`, and any other non-`const` objects that implement the interface.)

<br><br>

credit for this idea goes to @justinmc: https://github.com/flutter/flutter/issues/89127#issuecomment-2313187703
2024-09-09 21:49:09 +00:00
Valentin Vignal
15904ef9be
Add tests for sliver grid delegate with fixed cross axis count examples (#153500)
Contributes to https://github.com/flutter/flutter/issues/130459

It adds a test for
- `examples/api/lib/rendering/sliver_grid/sliver_grid_delegate_with_fixed_cross_axis_count.0.dart`
- `examples/api/lib/rendering/sliver_grid/sliver_grid_delegate_with_fixed_cross_axis_count.1.dart`

I also fixed a mistake in the documentation
2024-08-29 21:41:21 +00:00
Mansour Alhaddad
a43c401c67
Add test for error_widget.0_test.dart (#153103)
Add test for error_widget.0_test.dart which is listed in this issue 

related to this issue https://github.com/flutter/flutter/issues/130459
2024-08-26 18:11:02 +00:00
Pavlo Kochylo
a4b0d973fb
Added new constructor RefreshIndicator.noSpinner() (#152075)
This PR adds a new constructor to the RefreshIndicator's class, which is `noSpinner`.
The purpose of this new constructor is to create a RefreshIndicator that doesn't show a spinner when the user arms it by pulling.

The work is based on a partial that is here: https://github.com/flutter/flutter/pull/133507

I addressed the following issues reported in the PR above:
- in the example for `noSpinner`, arming the RefreshIndicator now shows a CircularProgressIndicator, instead of just printing text to the console;
- added a test for the new example;
- added a doc comment on the new constructor;

Fixes https://github.com/flutter/flutter/issues/132775
2024-08-23 20:37:24 +00:00
Justin McCandless
420755dcfa
Nested Navigator state restoration predictive back examples (#153723)
I've updated these two examples to support state restoration of the navigation stack and verified that they work with predictive back in the tests. This was motivated by a worry that users are not properly setting up their navigation and that our examples are misleading them in the name of simplicity.
2024-08-22 03:40:09 +00:00
Jamie Kerber
dae3a87d93
Implemented CupertinoButton new styles/sizes (fixes #92525) (#152845)
This PR fixes #92525 and introduces the following changes according to [latest iOS HIG](https://developer.apple.com/design/human-interface-guidelines/buttons#iOS-iPadOS):

- `CupertinoButton` now has a `size` property (type `enum CupertinoButtonSize`, values sm/md/lg, default `lg`) that allows the devs to apply new iOS 15+ button styles
- Previously `CupertinoButton` had a larger padding when no background color was specified. With the new HIG, that is no longer the case
- `CupertinoButton` now has a `.tinted` constructor that renders a translucent background (transparency % is brightness-dependent) and uses a different foreground color compared to `.filled`
- `CupertinoButton` now uses the `actionTextStyle` TextStyle from the given theme
- `CupertinoButton`'s child IconTheme's size will always be x1.2 the given TextStyle's size
- `CupertinoTextThemeData` now has a `actionSmallTextStyle` property to use with small buttons (including a default `_kDefaultActionSmallTextStyle` TextStyle)

Preview & example:

![image](https://github.com/user-attachments/assets/0985eb19-c091-41f5-bd98-0de196b7e403)

> **NOTE**: there is a discrepancy in dark mode button foreground color between the default CupertinoTheme and the HIG. A separate issue will be opened for this.

~EDIT: issue reported here https://github.com/flutter/flutter/issues/152846~
EDIT2: fixed by #153039 !

![image](https://github.com/user-attachments/assets/d671d7b4-bb2f-4b38-9464-ee1b04927304)

## Example
```dart
import 'package:flutter/cupertino.dart';

const Widget body = Row(
  mainAxisSize: MainAxisSize.min,
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    Icon(
      CupertinoIcons.play_fill,
    ),
    Text("Play"),
  ],
);

void main() =>
  runApp(
    CupertinoApp(
      home: Container(
        child: Wrap(
        direction: Axis.horizontal,
        children: <Widget>[
          // header
          Text(''),
          Text('Plain'),
          Text('Grey'),
          Text('Tinted'),
          Text('Filled'),
          // small
          Text('Small'),
          CupertinoButton(
            child: body,
            onPressed: () {},
            size: CupertinoButtonSize.small,
          ),
          CupertinoButton.tinted(
            child: body,
            onPressed: () {},
            size: CupertinoButtonSize.small,
            color: CupertinoColors.systemGrey,
          ),
          CupertinoButton.tinted(
            child: body,
            onPressed: () {},
            size: CupertinoButtonSize.small,
          ),
          CupertinoButton.filled(
            child: body,
            onPressed: () {},
            size: CupertinoButtonSize.small,
          ),
          // medium
          Text('Medium'),
          CupertinoButton(
            child: body,
            onPressed: () {},
            size: CupertinoButtonSize.medium,
          ),
          CupertinoButton.tinted(
            child: body,
            onPressed: () {},
            size: CupertinoButtonSize.medium,
            color: CupertinoColors.systemGrey,
          ),
          CupertinoButton.tinted(
            child: body,
            onPressed: () {},
            size: CupertinoButtonSize.medium,
          ),
          CupertinoButton.filled(
            child: body,
            onPressed: () {},
            size: CupertinoButtonSize.medium,
          ),
          // large
          Text('Large'),
          CupertinoButton(
            child: body,
            onPressed: () {},
            size: CupertinoButtonSize.large,
          ),
          CupertinoButton.tinted(
            child: body,
            onPressed: () {},
            color: CupertinoColors.systemGrey,
            size: CupertinoButtonSize.large,
          ),
          CupertinoButton.tinted(
            child: body,
            onPressed: () {},
            size: CupertinoButtonSize.large,
          ),
          CupertinoButton.filled(
            child: body,
            onPressed: () {},
            size: CupertinoButtonSize.large,
          ),
        ].map((Widget w) => SizedBox(width: 110, height: 70, child: Center(child: w))).toList(),
      ),
      )
    ),
  );

```

*List which issues are fixed by this PR. You must list at least one issue. An issue is not required if the PR fixes something trivial like a typo.*

*If you had to change anything in the [flutter/tests] repo, include a link to the migration guide as per the [breaking change policy].*
2024-08-12 19:26:39 +00:00
Michael Goderbauer
7c8feb94a5
Doc imports again (#152958)
https://github.com/flutter/flutter/issues/150800

The only remaining reports of `comment_references` are now because of the known issues listed in https://github.com/flutter/flutter/issues/150800.
2024-08-07 18:32:37 +00:00
Kishan Rathore
0f7bceb9c4
Style: Rename CupertinoSwitch activeColor and trackColor to activeTrackColor and InactiveTrackColor (#151367)
Style: Rename CupertinoSwitch `activeColor` and `trackColor` to `activeTrackColor` and `InactiveTrackColor`

Resolves #151256
2024-08-07 17:42:57 +00:00
Nate Wilson
0397e890be
Implement on clauses (#152706)
This pull request removes an `// ignore: avoid_catches_without_on_clauses` comment.

> [!NOTE]
> Diffs are super tiny if you do "hide whitespace"!
2024-08-06 01:54:52 +00:00
Nate Wilson
6ff806d74e
Use .fromMap() constructors in example code (#152535)
Currently, there are 21 `.resolveWith()` calls in example files.

This pull request changes 11 of them to use the new `.fromMap()` constructor. (Seven of them are now `const`!)

```dart
ListTile(
  iconColor: WidgetStateColor.fromMap(<WidgetStatesConstraint, Color>{
    WidgetState.disabled: Colors.red,
    WidgetState.selected: Colors.green,
    WidgetState.any:      Colors.black,
  }),
  // The same can be achieved using the .resolveWith() constructor.
  // The text color will be identical to the icon color above.
  textColor: WidgetStateColor.resolveWith((Set<WidgetState> states) {
    if (states.contains(WidgetState.disabled)) {
      return Colors.red;
    }
    if (states.contains(WidgetState.selected)) {
      return Colors.green;
    }
    return Colors.black;
  }),
),
```
2024-08-01 22:28:22 +00:00
Taha Tesser
bba6ea9a2d
Introduce TabBar.indicatorAnimation to customize tab indicator animation (#151746)
fixes [Add ability to customize `TabBar` indicator animation](https://github.com/flutter/flutter/issues/150508)

Similar option exist on Android
https://developer.android.com/reference/com/google/android/material/tabs/TabLayout#setTabIndicatorAnimationMode(int)

### Dartpad Example Preview
<img width="874" alt="Screenshot 2024-07-12 at 17 36 08" src="https://github.com/user-attachments/assets/e349c5aa-ee5d-46ce-9e44-4f02346603bd">

### Linear vs Elastic tab indicator animation

https://github.com/user-attachments/assets/d7ae3ae4-ae52-4ccd-89b1-75908bf8a34d
2024-07-26 11:54:28 +00:00
Huy
7d5c1c04fb
Enhances intuitiveness of RawMagnifier's example (#150308)
### Demo

| Before | After |
| --------------- | --------------- |
<video src="https://github.com/flutter/flutter/assets/104349824/ee6d45f1-bcf0-4136-8d1d-a642e0767322"/> | <video src="https://github.com/flutter/flutter/assets/104349824/1e2bb33d-40f1-4cf6-9999-f67bef638633"/>

### Related issue

Fixes https://github.com/flutter/flutter/issues/150307
2024-07-19 14:09:18 +00:00
Qun Cheng
844eb2fe76
Create CarouselView widget - Part 2 (#149775)
This PR is to create `Carousel.weighted` so the size of each carousel item is based on a list of weights. While scrolling, item sizes are changing dynamically based on the scrolling progress.

https://github.com/flutter/flutter/assets/36861262/181472b0-6f8b-48e7-b191-ab5f7c88c0c8
2024-07-17 19:56:01 +00:00
Victor Sanni
cb4ba2fddc
Add example for CupertinoCheckbox (#151779) 2024-07-16 16:54:02 +00:00
Michael Goderbauer
43f3252c82
docimports for API samples (#151606)
Part of https://github.com/flutter/flutter/issues/150800

Turns out: None of these actually need any docImports. They just had broken references.
2024-07-11 20:36:55 +00:00
Nate Wilson
b713445298
Factor out deprecated names in example code (#151374)
This PR contains:
- 3 instances of `colorScheme.background` → `colorScheme.surface`
- and a whole bunch of `MaterialState` → `WidgetState`

As of yet, no changes have been made to example test files or the [examples/api/lib/material/material_state/](0b2a8e589e/examples/api/lib/material/material_state) directory.

(related: #151373)
2024-07-08 19:06:54 +00:00
Vincent Velociter
6e246ac854
Cupertino transparent navigation bars (#149102)
This PR is making the `CupertinoNavigationBar` and `CupertinoSliverNavigationBar` appear transparent as long as the content is not scrolled under them, so they look like standard iOS apps nav bars.

https://github.com/flutter/flutter/assets/423393/eee2700b-2a91-4577-922c-6163d47cb357

https://github.com/flutter/flutter/assets/423393/3847f2b5-0dac-4d5e-aa6f-03c1d2893e30

<details>
  <summary>Demo app code</summary>
  
  ```dart
import 'package:flutter/cupertino.dart';

/// Flutter code sample for [CupertinoTabScaffold].

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

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

  @override
  State<TabScaffoldApp> createState() => _TabScaffoldAppState();
}

class _TabScaffoldAppState extends State<TabScaffoldApp> {
  Brightness _brightness = Brightness.light;

  @override
  Widget build(BuildContext context) {
    return CupertinoApp(
      theme: CupertinoThemeData(brightness: _brightness),
      home: TabScaffoldExample(
          brightness: _brightness, onBrightnessToggle: _toggleBrightness),
    );
  }

  void _toggleBrightness() {
    setState(() {
      _brightness =
          _brightness == Brightness.light ? Brightness.dark : Brightness.light;
    });
  }
}

class TabScaffoldExample extends StatefulWidget {
  const TabScaffoldExample(
      {required this.brightness, required this.onBrightnessToggle, super.key});

  final VoidCallback onBrightnessToggle;
  final Brightness brightness;

  @override
  State<TabScaffoldExample> createState() => _TabScaffoldExampleState();
}

class _TabScaffoldExampleState extends State<TabScaffoldExample> {
  @override
  Widget build(BuildContext context) {
    return CupertinoTabScaffold(
      tabBar: CupertinoTabBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.search_circle_fill),
            label: 'Explore',
          ),
          BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.person_fill),
            label: 'Profile',
          ),
          BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.settings_solid),
            label: 'Settings',
          ),
        ],
      ),
      tabBuilder: (BuildContext context, int index) {
        return CupertinoTabView(
          builder: (BuildContext context) {
            return CupertinoPageScaffold(
              backgroundColor: index == 3
                  ? CupertinoColors.secondarySystemBackground
                      .resolveFrom(context)
                  : null,
              child: CustomScrollView(
                slivers: [
                  CupertinoSliverNavigationBar(
                    largeTitle: Text('Tab $index'),
                    initiallyTransparent: index != 2,
                    trailing: CupertinoButton(
                      padding: EdgeInsets.zero,
                      onPressed: widget.onBrightnessToggle,
                      child: Icon(
                        widget.brightness == Brightness.light
                            ? CupertinoIcons.moon_stars
                            : CupertinoIcons.sun_max,
                      ),
                    ),
                  ),
                  SliverSafeArea(
                    top: false,
                    sliver: SliverList.list(
                      children: [
                        CupertinoButton(
                          child: const Text('Next page'),
                          onPressed: () {
                            Navigator.of(context).push(
                              CupertinoPageRoute<void>(
                                builder: (BuildContext context) {
                                  return CupertinoPageScaffold(
                                    navigationBar: CupertinoNavigationBar(
                                      middle: Text('Inner page of tab $index'),
                                    ),
                                    child: ListView(
                                      children: [
                                        Center(
                                          child: CupertinoButton(
                                            child: const Text('Back'),
                                            onPressed: () {
                                              Navigator.of(context).pop();
                                            },
                                          ),
                                        ),
                                        if (index == 0) const _LongList(),
                                        const SizedBox(height: 20),
                                      ],
                                    ),
                                  );
                                },
                              ),
                            );
                          },
                        ),
                        if (index == 1) const _LongList(),
                        const SizedBox(height: 20),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }
}

class _LongList extends StatelessWidget {
  const _LongList();

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        for (int i = 0; i < 50; i++) ...[
          CupertinoListTile(
            leading: const Icon(CupertinoIcons.book),
            title: Text('Bookstore item $i'),
          ),
        ],
      ],
    );
  }
}
  ```
</details>

This is the continuation of https://github.com/flutter/flutter/pull/142439.

I tried to keep the simplest API possible, so it's only introducing a new `automaticBackgroundVisibility` boolean parameter. 

In the implementation I had to use the `CupertinoPageScaffold` background color to make it look transparent instead of a 0 opacity, because of issues with route transitions.

I used an `InheritedWidget` so the nav bar is always getting the right background color from the parent scaffold, whether it is overridden or not. It would probably be better to make the inherited widget private but we'd need to move all the nav bar code to the same file as the scaffold, so for now I've just hidden it from the export. Let me know if it is okay to do that.

This PR is not dealing with the bottom tab bar, because the same [straightforward approach](dde8ec6dc7) doesn't work here. The problem is that the scroll notification is sent only when the scroll view is created or updated, so it doesn't work if one pushes a screen and navigates back.

Issues:
- #78607 
- #60411
2024-07-03 20:35:27 +00:00
Hans Muller
abd7cd0528
PinnedHeaderSliver example based on the iOS Settings AppBar (#151205)
A relatively elaborate PinnedSliverHeader example which creates an app bar that's similar to the one that appears in the iOS Settings app. In this example the pinned header starts out transparent and the first item in the list serves as the app's "Settings" title. When the title item has been scrolled completely behind the pinned header, the header animates its opacity from 0 to 1 and its (centered) "Settings" title appears. The fact that the header's opacity depends on the height of the title item - which is unknown until the list has been laid out - necessitates monitoring its SliverConstraints.scrollExtent from a scroll NotificationListener. 

https://github.com/flutter/flutter/assets/1377460/539e2591-d0d7-4508-8ce8-4b8f587d7648
2024-07-03 20:06:16 +00:00
Hans Muller
d1e150099e
SliverFloatingHeader (#151145)
A sliver that shows its [child] when the user scrolls forward and hides it when the user scrolls backwards. Similar headers can be found in  Google Photos and Facebook.

This sliver is preferable to the general purpose SliverPersistentHeader for its relatively narrow use case because there's no need to create a SliverPersistentHeaderDelegate or to predict the header's size.

https://github.com/flutter/flutter/assets/1377460/82b67dfb-5d38-4adf-9415-fc8527d0eb9f
2024-07-03 19:52:52 +00:00
Michael Goderbauer
56835d6039
Fix references in examples (#151204)
Part of https://github.com/flutter/flutter/issues/150800
2024-07-03 17:56:48 +00:00
Snoppy
65cd7cf7b2
chore: fix typos and link broken (#150402)
**fix some typos and link broken**
2024-07-03 17:10:19 +00:00
Hans Muller
acb41f3174
ScrollEndNotification example: auto-scroll based on RenderSliver constraints and geometry (#143538)
Adds a new ScrollNotificationEnd example that demonstrates how to trigger an auto-scroll based on an individual sliver's `SliverConstraints` and `SliverGeometry`. 

Then new example auto-scrolls one special "aligned item" sliver to the top or bottom of the viewport, whenever it's partially visible (because it overlaps the top or bottom of the viewport). This example differs from the existing ScrollEndNotification example because the layout of the to-be aligned sliver is retrieved from its `RenderSliver` via a
GlobalKey.  The new example does not rely on all of the list items having the same extent.
2024-07-02 18:46:19 +00:00
Tong Mu
98fb56fc05
Remove reference to MaterialApp and showCupertinoModalPopup from CupertinoAlertDialog (#150725)
This PR removes the usage of Material widgets from unit tests of `CupertinoAlertDialog`. Other than it being just wrong, it also introduces bad behavior, such as the scroll view can't be overscrolled so that the overscroll behavior can't be tested.
* Since there are no longer M2 or M3 variants of tests, I straight up rewrote the unit tests for "default look" with similar tests as those of `CupertinoActionSheet` ([here](https://github.com/flutter/flutter/blob/master/packages/flutter/test/cupertino/action_sheet_test.dart#L21))

This PR also replaces `showCupertinoModalPopup` with `showCupertinoDialog` in `CupertinoAlertDialog`'s example code. The former should only be used by `CupertinoActionSheet`, which has a different animation from the correct `showCupertinoDialog`.
2024-06-25 22:45:05 +00:00
Huy
47689616a9
Add an example for CupertinoPopupSurface (#150357)
### Demo

https://github.com/flutter/flutter/assets/104349824/61cd4c96-e01e-4fad-b270-acd7bb55d995

### Related issue

Fixes https://github.com/flutter/flutter/issues/150353
2024-06-25 11:20:34 +00:00
derdilla
0674f46e9f
Test InputDecoration API examples (#148560)
Add tests for `InputDecoration` API example as part of #130459. Updates examples that use the deprecated MaterialState to use WidgetState. Tests files: `input_decoration.0.dart`, `input_decoration.1.dart`, `input_decoration.2.dart`, `input_decoration.3.dart`, `input_decoration.widget_state.0.dart`, `input_decoration.widget_state.1.dart`, `input_decoration.prefix_icon_constraints.0.dart`, `input_decoration.suffix_icon_constraints.0.dart`, and `input_decoration.label.0.dart`
2024-06-20 16:02:07 +00:00
Hasan M. Hallak
f54dfcd27d
add forceErrorText to FormField & TextFormField. (#132903)
Introducing the `forceErrorText` property to both `FormField` and `TextFormField`. With this addition, we gain the capability to trigger an error state and provide an error message without invoking the `validator` method.

While the idea of making the `Validator` method work asynchronously may be appealing, it could introduce significant complexity to our current form field implementation. Additionally, this approach might not be suitable for all developers, as discussed by @justinmc  in this [comment](https://github.com/flutter/flutter/issues/56414#issuecomment-624960263).

This PR try to address this issue by adding `forceErrorText` property allowing us to force the error to the `FormField` or `TextFormField` at our own base making it possible to preform some async operations without the need for any hacks while keep the ability to check for errors if we call `formKey.currentState!.validate()`.

Here is an example:

<details> <summary>Code Example</summary>  

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

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

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final key = GlobalKey<FormState>();
  String? forcedErrorText;

  Future<void> handleValidation() async {
    // simulate some async work..
    await Future.delayed(const Duration(seconds: 3));

    setState(() {
      forcedErrorText = 'this username is not available.';
    });

    // wait for build to run and then check.
    //
    // this is not required though, as the error would already be showing.
    WidgetsBinding.instance.addPostFrameCallback((_) {
      print(key.currentState!.validate());
    });
  }

  @override
  Widget build(BuildContext context) {
    print('build');
    return Scaffold(
      floatingActionButton: FloatingActionButton(onPressed: handleValidation),
      body: Form(
        key: key,
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 30),
                child: TextFormField(
                  forceErrorText: forcedErrorText,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
```
</details>

Related to #9688 & #56414.

Happy to hear your thoughts on this.
2024-06-18 17:52:21 +00:00
Kate Lovett
9b6813f4da
Reland TreeSliver (#149839)
Reland of https://github.com/flutter/flutter/pull/147171

It was reverted for a failing unit test that had passed in presubmit. Hopefully this sticks better.
Also fixed leaks in 37b10adc90
2024-06-17 19:49:05 +00:00
Taha Tesser
f56e0c2845
[Reland] Introduce ChipAnimationStyle to override default chips animations durations (#149876)
Reland - https://github.com/flutter/flutter/pull/149245

---

fixes [Custom backgroundColor on Chip makes it flicker between state transitions](https://github.com/flutter/flutter/issues/146730)

### Example preview
![Screenshot 2024-05-28 at 17 40 00](https://github.com/flutter/flutter/assets/48603081/b9117ed2-5afa-4d65-93ae-aa866772ffa1)

https://github.com/flutter/flutter/assets/48603081/a4949ce7-f38b-4251-8201-ecc570ec447c
2024-06-13 19:28:21 +00:00
Greg Spencer
966d2b9223
Fix ColorScheme example and tests (#150018)
## Description

This fixes the `ColorScheme` example to actually work.  The test had wrapped the app in an additional `MaterialApp`, which allowed the tests to work, but the real problem was using a `context` that was outside the `MaterialApp` to open the bottom sheet, which caused an exception when you actually try to run it interactively.

This fixes the example and the test.

## Tests
 - Fixed the test to not artificially add a second `MaterialApp`.
2024-06-12 05:07:23 +00:00
Hans Muller
9ce0a9e510
PinnedHeaderSliver (#143196)
A sliver that remains “pinned” to the top of the scroll view. Subsequent slivers scroll behind it. Typically the sliver is created as the first item in the list however it can be inserted anywhere and it will always stop at the top of the scroll view. When the scrolling axis is vertical, the PinnedHeaderSliver’s height is defined by its widget child. Multiple PinnedHeaderSlivers will layout one after the other, once they've scrolled to the top.

This sliver is preferable to the general purpose SliverPersistentHeader - for its relatively narrow use case - because there's no need to create a [SliverPersistentHeaderDelegate] or to predict the header's size.

Here's a [working demo in DartPad](https://dartpad.dev/?id=3b3f24c14fa201f752407a21ca9c9456).

https://github.com/flutter/flutter/assets/1377460/943f2e02-8e73-48b7-90be-61168978ff71

Related sliver utility PRs: https://github.com/flutter/flutter/pull/143538, https://github.com/flutter/flutter/pull/143325, https://github.com/flutter/flutter/pull/127340.
2024-06-07 21:27:06 +00:00